summaryrefslogtreecommitdiffstats
path: root/filters/kspread/csv/csvexport.cpp
blob: ceeb8b5ece5548fb2f6fa4974fc279c29d1aa130 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
/* This file is part of the KDE project
   Copyright (C) 2000 David Faure <faure@kde.org>
   Copyright (C) 2004 Nicolas GOUTTE <goutte@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
*/

#include <csvexport.h>

#include <tqfile.h>
#include <tqtextcodec.h>

#include <kdebug.h>
#include <tdemessagebox.h>
#include <kgenericfactory.h>
#include <KoFilterChain.h>
#include <KoFilterManager.h>

#include <kspread_map.h>
#include <kspread_sheet.h>
#include <kspread_doc.h>
#include <kspread_view.h>
#include <selection.h>

#include <csvexportdialog.h>

using namespace KSpread;

typedef KGenericFactory<CSVExport, KoFilter> CSVExportFactory;
K_EXPORT_COMPONENT_FACTORY( libcsvexport, CSVExportFactory( "kofficefilters" ) )

class Cell
{
 public:
  int row, col;
  TQString text;

  bool operator < ( const Cell & c ) const
  {
    return row < c.row || ( row == c.row && col < c.col );
  }
  bool operator == ( const Cell & c ) const
  {
    return row == c.row && col == c.col;
  }
};


CSVExport::CSVExport( KoFilter *, const char *, const TQStringList & )
  : KoFilter(), m_eol("\n")
{
}

TQString CSVExport::exportCSVCell( Sheet const * const sheet, int col, int row, TQChar const & textQuote, TQChar csvDelimiter )
{
  // This function, given a cell, returns a string corresponding to its export in CSV format
  // It proceeds by:
  //  - getting the value of the cell, if any
  //  - protecting quote characters within cells, if any
  //  - enclosing the cell in quotes if the cell is non empty

  KSpread::Cell const * const cell = sheet->cellAt( col, row );
  TQString text;

  if ( !cell->isDefault() && !cell->isEmpty() )
  {
    if ( cell->isFormula() )
        text = cell->strOutText();
    else if ( !cell->link().isEmpty() )
        text = cell->text(); // untested
    else if( cell->isTime() )
        text = cell->value().asTime().toString("hh:mm:ss");
    else if( cell->isDate() )
        text = cell->value().asDate().toString("yyyy-MM-dd");
    else
        text = cell->strOutText();
  }

  // quote only when needed (try to mimic excel)
  bool quote = false;
  if ( !text.isEmpty() )
  {
    if ( text.find( textQuote ) != -1 )
    {
      TQString doubleTextQuote(textQuote);
      doubleTextQuote.append(textQuote);
      text.replace(textQuote, doubleTextQuote);
      quote = true;

    } else if ( text[0].isSpace() || text[text.length()-1].isSpace() )
      quote = true;
    else if ( text.find( csvDelimiter ) != -1 )
      quote = true;
    else if ( text.find( "\n" ) != -1 || text.find( "\r" ) != -1 )
      quote = true;
  }

  if ( quote ) {
    text.prepend(textQuote);
    text.append(textQuote);
  }

  return text;
}

// The reason why we use the KoDocument* approach and not the TQDomDocument
// approach is because we don't want to export formulas but values !
KoFilter::ConversionStatus CSVExport::convert( const TQCString & from, const TQCString & to )
{
  kdDebug(30501) << "CSVExport::convert" << endl;
  KoDocument* document = m_chain->inputDocument();

  if ( !document )
    return KoFilter::StupidError;

  if ( !::tqqt_cast<const KSpread::Doc *>( document ) )
  {
    kdWarning(30501) << "document isn't a KSpread::Doc but a " << document->className() << endl;
    return KoFilter::NotImplemented;
  }
  if ( ( to != "text/x-csv" && to != "text/plain" ) || from != "application/x-kspread" )
  {
    kdWarning(30501) << "Invalid mimetypes " << to << " " << from << endl;
    return KoFilter::NotImplemented;
  }

  Doc const * const ksdoc = static_cast<const Doc *>(document);

  if ( ksdoc->mimeType() != "application/x-kspread" )
  {
    kdWarning(30501) << "Invalid document mimetype " << ksdoc->mimeType() << endl;
    return KoFilter::NotImplemented;
  }

  CSVExportDialog *expDialog = 0;
  if (!m_chain->manager()->getBatchMode())
  {
    expDialog= new CSVExportDialog( 0 );

    if (!expDialog)
    {
      kdError(30501) << "Dialog has not been created! Aborting!" << endl;
      return KoFilter::StupidError;
    }
    expDialog->fillSheet( ksdoc->map() );

    if ( !expDialog->exec() )
    {
      delete expDialog;
      return KoFilter::UserCancelled;
    }
  }

  TQTextCodec* codec = 0;
  TQChar csvDelimiter;
  if (expDialog)
  {
    codec = expDialog->getCodec();
    if ( !codec )
    {
      delete expDialog;
      return KoFilter::StupidError;
    }
    csvDelimiter = expDialog->getDelimiter();
    m_eol = expDialog->getEndOfLine();
  }
  else
  {
    codec = TQTextCodec::codecForName("UTF-8");
    csvDelimiter = ',';
  }


  // Now get hold of the sheet to export
  // (Hey, this could be part of the dialog too, choosing which sheet to export....
  //  It's great to have parametrable filters... IIRC even MSOffice doesn't have that)
  // Ok, for now we'll use the first sheet - my document has only one sheet anyway ;-)))

  bool first = true;
  TQString str;
  TQChar textQuote;
  if (expDialog)
    textQuote = expDialog->getTextQuote();
  else
    textQuote = '"';

  if ( expDialog && expDialog->exportSelectionOnly() )
  {
    kdDebug(30501) << "Export as selection mode" << endl;
    View const * const view = static_cast<View*>(ksdoc->views().getFirst());

    if ( !view ) // no view if embedded document
    {
      delete expDialog;
      return KoFilter::StupidError;
    }

    Sheet const * const sheet = view->activeSheet();

    TQRect selection = view->selectionInfo()->lastRange();
    // Compute the highest row and column indexes (within the selection)
    // containing non-empty cells, respectively called CSVMaxRow CSVMaxCol.
    // The CSV will have CSVMaxRow rows, all with CSVMaxCol columns
    int right       = selection.right();
    int bottom      = selection.bottom();
    int CSVMaxRow   = 0;
    int CSVMaxCol   = 0;

    for ( int idxRow = 1, row = selection.top(); row <= bottom; ++row, ++idxRow )
    {
      for ( int idxCol = 1, col = selection.left(); col <= right; ++col, ++idxCol )
      {
        if( ! sheet->cellAt( col, row )->isEmpty() )
        {
          if ( idxRow > CSVMaxRow )
            CSVMaxRow = idxRow;

          if ( idxCol > CSVMaxCol )
            CSVMaxCol = idxCol;
        }
      }
    }

    for ( int idxRow = 1, row = selection.top();
          row <= bottom && idxRow <= CSVMaxRow; ++row, ++idxRow )
    {
      int idxCol = 1;
      for ( int col = selection.left();
            col <= right && idxCol <= CSVMaxCol; ++col, ++idxCol )
      {
        str += exportCSVCell( sheet, col, row, textQuote, csvDelimiter );

        if ( idxCol < CSVMaxCol )
          str += csvDelimiter;
      }

      // This is to deal with the case of non-rectangular selections 
      for ( ; idxCol < CSVMaxCol; ++idxCol )
          str += csvDelimiter;

      str += m_eol;
    }
  }
  else
  {
    kdDebug(30501) << "Export as full mode" << endl;
    TQPtrListIterator<Sheet> it( ksdoc->map()->sheetList() );
    for( ; it.current(); ++it )
    {
      Sheet const * const sheet = it.current();

      if (expDialog && !expDialog->exportSheet( sheet->sheetName() ) )
      {
        continue;
      }

      // Compute the highest row and column indexes containing non-empty cells,
      // respectively called CSVMaxRow CSVMaxCol.
      // The CSV will have CSVMaxRow rows, all with CSVMaxCol columns
      int sheetMaxRow = sheet->maxRow();
      int sheetMaxCol = sheet->maxColumn();
      int CSVMaxRow   = 0;
      int CSVMaxCol   = 0;

      for ( int row = 1 ; row <= sheetMaxRow ; ++row)
      {
        for ( int col = 1 ; col <= sheetMaxCol ; col++ )
        {
          if( ! sheet->cellAt( col, row )->isEmpty() )
          {
            if ( row > CSVMaxRow )
              CSVMaxRow = row;

            if ( col > CSVMaxCol )
              CSVMaxCol = col;
          }
        }
      }

      // Skip the sheet altogether if it is empty
      if ( CSVMaxRow + CSVMaxCol == 0)
        continue;

      kdDebug(30501) << "Max row x column: " << CSVMaxRow << " x " << CSVMaxCol << endl;

      // Print sheet separators, except for the first sheet
      if ( !first || ( expDialog && expDialog->printAlwaysSheetDelimiter() ) )
      {
        if ( !first)
          str += m_eol;

	TQString name;
	if (expDialog)
	  name = expDialog->getSheetDelimiter();
	else
	  name = "********<SHEETNAME>********";
        const TQString tname( i18n("<SHEETNAME>") );
        int pos = name.find( tname );
        if ( pos != -1 )
        {
          name.replace( pos, tname.length(), sheet->sheetName() );
        }
        str += name;
        str += m_eol;
        str += m_eol;
      }

      first = false;


      // this is just a bad approximation which fails for documents with less than 50 rows, but
      // we don't need any progress stuff there anyway :) (Werner)
      int value = 0;
      int step  = CSVMaxRow > 50 ? CSVMaxRow/50 : 1;

      // Print the CSV for the sheet data
      for ( int row = 1, i = 1 ; row <= CSVMaxRow ; ++row, ++i )
      {
        if ( i > step )
        {
          value += 2;
          emit sigProgress(value);
          i = 0;
        }

        TQString collect;  // buffer delimiters while reading empty cells

        for ( int col = 1 ; col <= CSVMaxCol ; col++ )
        {
          const TQString txt = exportCSVCell( sheet, col, row, textQuote, csvDelimiter );

          // if we encounter a non-empty cell, commit the buffered delimiters
	  if (!txt.isEmpty()) {
	    str += collect + txt;
	    collect = TQString();
	  }

          collect += csvDelimiter;
        }
        // Here, throw away buffered delimiters. They're trailing and therefore
	// superfluous.

        str += m_eol;
      }
    }
  }

  emit sigProgress(100);

  TQFile out(m_chain->outputFile());
  if ( !out.open( IO_WriteOnly ) )
  {
    kdError(30501) << "Unable to open output file!" << endl;
    out.close();
    delete expDialog;
    return KoFilter::StupidError;
  }

  TQTextStream outStream( &out );
  outStream.setCodec( codec );

  outStream << str;

  out.close();
  delete expDialog;
  return KoFilter::OK;
}

#include <csvexport.moc>