File: csvexport.cc

package info (click to toggle)
calligra 1%3A25.04.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 309,164 kB
  • sloc: cpp: 667,890; xml: 126,105; perl: 2,724; python: 2,497; yacc: 1,817; ansic: 1,326; sh: 1,223; lex: 1,107; javascript: 495; makefile: 24
file content (314 lines) | stat: -rw-r--r-- 10,803 bytes parent folder | download | duplicates (2)
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
/* This file is part of the KDE project
   SPDX-FileCopyrightText: 2000 David Faure <faure@kde.org>
   SPDX-FileCopyrightText: 2004 Nicolas GOUTTE <goutte@kde.org>

   SPDX-License-Identifier: LGPL-2.0-or-later
*/

#include <csvexport.h>

#include <QFile>

#include <KPluginFactory>
#include <KoFilterChain.h>
#include <KoFilterManager.h>
#include <KoPart.h>

#include <sheets/engine/Localization.h>
#include <sheets/engine/CalculationSettings.h>
#include <sheets/core/CellStorage.h>
#include <sheets/core/Map.h>
#include <sheets/core/Sheet.h>
#include <sheets/ui/Selection.h>
#include <sheets/part/Doc.h>
#include <sheets/part/View.h>

#include "csvexportdialog.h"

using namespace Calligra::Sheets;

K_PLUGIN_FACTORY_WITH_JSON(CSVExportFactory, "calligra_filter_sheets2csv.json", registerPlugin<CSVExport>();)

Q_LOGGING_CATEGORY(lcCsvExport, "calligra.filter.csv.export")

class Cell
{
public:
    int row, col;
    QString 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(QObject* parent, const QVariantList &)
        : KoFilter(parent), m_eol("\n")
{
}

QString CSVExport::exportCSVCell(const Calligra::Sheets::Doc* doc, Sheet *sheet,
                                 int col, int row, QChar const & textQuote, QChar 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

    Q_UNUSED(doc);
    const Calligra::Sheets::Cell cell(sheet, col, row);
    QString text;

    if (!cell.isDefault() && !cell.isEmpty()) {
        if (cell.isFormula())
            text = cell.displayText();
        else if (!cell.link().isEmpty())
            text = cell.userInput(); // untested
        else if (cell.isTime())
            text = sheet->map()->calculationSettings()->locale()->formatTime(cell.value().asTime(), "hh:mm:ss"); // FIXME duration?
        else if (cell.isDate())
            text = cell.value().asDate(sheet->map()->calculationSettings()).toString("yyyy-MM-dd");
        else
            text = cell.displayText();
    }

    // quote only when needed (try to mimic excel)
    bool quote = false;
    if (!text.isEmpty()) {
        if (text.indexOf(textQuote) != -1) {
            QString 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.indexOf(csvDelimiter) != -1)
            quote = true;
    }

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

    return text;
}

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

    if (!document)
        return KoFilter::StupidError;

    if (!qobject_cast<const Calligra::Sheets::Doc *>(document)) {
        qWarning(lcCsvExport) << "document isn't a Calligra::Sheets::Doc but a " << document->metaObject()->className();
        return KoFilter::NotImplemented;
    }
    if ((to != "text/csv" && to != "text/plain") || from != "application/vnd.oasis.opendocument.spreadsheet") {
        qWarning(lcCsvExport) << "Invalid mimetypes " << to << " " << from;
        return KoFilter::NotImplemented;
    }

    Doc *ksdoc = qobject_cast<Doc *>(document);

    if (ksdoc->mimeType() != "application/vnd.oasis.opendocument.spreadsheet") {
        qWarning(lcCsvExport) << "Invalid document mimetype" << ksdoc->mimeType();
        return KoFilter::NotImplemented;
    }

    std::unique_ptr<CSVExportDialog> expDialog;
    if (!m_chain->manager()->getBatchMode()) {
        expDialog = std::make_unique<CSVExportDialog>(nullptr);
        expDialog->fillSheet(ksdoc->map());

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

    QChar csvDelimiter;
    if (expDialog) {
        csvDelimiter = expDialog->getDelimiter();
        m_eol = expDialog->getEndOfLine();
    } else {
        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;
    QString str;
    QChar textQuote;
    if (expDialog)
        textQuote = expDialog->getTextQuote();
    else
        textQuote = '"';

    if (expDialog && expDialog->exportSelectionOnly()) {
        qDebug(lcCsvExport) << "Export as selection mode";
        View *view = ksdoc->documentPart()->views().isEmpty() ? nullptr : static_cast<View*>(ksdoc->documentPart()->views().first());

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

        Sheet *sheet = view->activeSheet();

        QRect selection = view->selection()->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 (!Calligra::Sheets::Cell(sheet, 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(ksdoc, 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 {
        qDebug(lcCsvExport) << "Export as full mode";
        for(SheetBase *bsheet : ksdoc->map()->sheetList()) {
            Sheet *sheet = dynamic_cast<Sheet *>(bsheet);
            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->cellStorage()->rows();
            int sheetMaxCol = sheet->cellStorage()->columns();
            int CSVMaxRow   = 0;
            int CSVMaxCol   = 0;

            for (int row = 1 ; row <= sheetMaxRow ; ++row) {
                for (int col = 1 ; col <= sheetMaxCol ; col++) {
                    if (!Calligra::Sheets::Cell(sheet, 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;

            qDebug(lcCsvExport) << "Max row x column:" << CSVMaxRow << " x" << CSVMaxCol;

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

                QString name;
                if (expDialog)
                    name = expDialog->getSheetDelimiter();
                else
                    name = "********<SHEETNAME>********";
                const QString tname(i18n("<SHEETNAME>"));
                int pos = name.indexOf(tname);
                if (pos != -1) {
                    name.replace(pos, tname.length(), sheet->sheetName());
                }
                str += name + m_eol + 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;
                    Q_EMIT sigProgress(value);
                    i = 0;
                }

                QString collect;  // buffer delimiters while reading empty cells

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

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

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

                str += m_eol;
            }
        }
    }

    Q_EMIT sigProgress(100);

    QFile out(m_chain->outputFile());
    if (!out.open(QIODevice::WriteOnly)) {
        qCritical(lcCsvExport) << "Unable to open output file!" << Qt::endl;
        out.close();
        return KoFilter::StupidError;
    }

    QTextStream outStream(&out);
    outStream << str;
    out.close();

    return KoFilter::OK;
}

#include <csvexport.moc>