From 534490e9b2ad6c5f59f492eaafa388a404d1b6bf Mon Sep 17 00:00:00 2001 From: Debao Zhang Date: Thu, 19 Mar 2020 01:33:41 +0800 Subject: [PATCH] Make use of clang-format Change-Id: I71bbf133223931eddb0c7e568cc0b99ecf807fa1 --- _clang-format | 25 + examples/xlsx/calendar/main.cpp | 47 +- examples/xlsx/chart/main.cpp | 12 +- examples/xlsx/chartsheet/main.cpp | 6 +- examples/xlsx/conditionalformatting/main.cpp | 4 +- examples/xlsx/definename/main.cpp | 6 +- examples/xlsx/demo/main.cpp | 93 +-- examples/xlsx/extractdata/main.cpp | 40 +- examples/xlsx/formulas/main.cpp | 28 +- examples/xlsx/image/main.cpp | 6 +- examples/xlsx/mergecells/main.cpp | 1 - examples/xlsx/numberformat/main.cpp | 22 +- examples/xlsx/rowcolumn/main.cpp | 14 +- examples/xlsx/style/main.cpp | 6 +- examples/xlsx/worksheetoperations/main.cpp | 6 +- examples/xlsx/xlsxwidget/main.cpp | 3 +- examples/xlsx/xlsxwidget/xlsxsheetmodel.cpp | 19 +- examples/xlsx/xlsxwidget/xlsxsheetmodel.h | 4 +- src/xlsx/xlsxabstractooxmlfile.cpp | 16 +- src/xlsx/xlsxabstractooxmlfile.h | 6 +- src/xlsx/xlsxabstractooxmlfile_p.h | 4 +- src/xlsx/xlsxabstractsheet.cpp | 6 +- src/xlsx/xlsxabstractsheet.h | 13 +- src/xlsx/xlsxabstractsheet_p.h | 1 - src/xlsx/xlsxcell.cpp | 30 +- src/xlsx/xlsxcell.h | 20 +- src/xlsx/xlsxcell_p.h | 2 +- src/xlsx/xlsxcellformula.cpp | 52 +- src/xlsx/xlsxcellformula.h | 18 +- src/xlsx/xlsxcellformula_p.h | 9 +- src/xlsx/xlsxcellrange.cpp | 23 +- src/xlsx/xlsxcellrange.h | 15 +- src/xlsx/xlsxcellreference.cpp | 29 +- src/xlsx/xlsxcellreference.h | 11 +- src/xlsx/xlsxchart.cpp | 282 +++++---- src/xlsx/xlsxchart.h | 5 +- src/xlsx/xlsxchart_p.h | 35 +- src/xlsx/xlsxchartsheet.cpp | 29 +- src/xlsx/xlsxchartsheet.h | 1 - src/xlsx/xlsxchartsheet_p.h | 1 - src/xlsx/xlsxcolor.cpp | 30 +- src/xlsx/xlsxcolor_p.h | 6 +- src/xlsx/xlsxconditionalformatting.cpp | 220 ++++--- src/xlsx/xlsxconditionalformatting.h | 36 +- src/xlsx/xlsxconditionalformatting_p.h | 21 +- src/xlsx/xlsxcontenttypes.cpp | 90 +-- src/xlsx/xlsxcontenttypes_p.h | 4 +- src/xlsx/xlsxdatavalidation.cpp | 59 +- src/xlsx/xlsxdatavalidation.h | 32 +- src/xlsx/xlsxdatavalidation_p.h | 6 +- src/xlsx/xlsxdocpropsapp.cpp | 61 +- src/xlsx/xlsxdocpropsapp_p.h | 5 +- src/xlsx/xlsxdocpropscore.cpp | 96 +-- src/xlsx/xlsxdocpropscore_p.h | 3 +- src/xlsx/xlsxdocument.cpp | 221 ++++--- src/xlsx/xlsxdocument.h | 21 +- src/xlsx/xlsxdocument_p.h | 7 +- src/xlsx/xlsxdrawing.cpp | 18 +- src/xlsx/xlsxdrawinganchor.cpp | 134 ++-- src/xlsx/xlsxdrawinganchor_p.h | 34 +- src/xlsx/xlsxformat.cpp | 149 +++-- src/xlsx/xlsxformat.h | 39 +- src/xlsx/xlsxformat_p.h | 18 +- src/xlsx/xlsxglobal.h | 16 +- src/xlsx/xlsxmediafile.cpp | 12 +- src/xlsx/xlsxmediafile_p.h | 5 +- src/xlsx/xlsxnumformatparser.cpp | 8 +- src/xlsx/xlsxrelationships.cpp | 54 +- src/xlsx/xlsxrelationships_p.h | 7 +- src/xlsx/xlsxrichstring.cpp | 41 +- src/xlsx/xlsxrichstring.h | 1 + src/xlsx/xlsxsharedstrings.cpp | 97 +-- src/xlsx/xlsxsharedstrings_p.h | 10 +- src/xlsx/xlsxsimpleooxmlfile.cpp | 3 +- src/xlsx/xlsxsimpleooxmlfile_p.h | 1 - src/xlsx/xlsxstyles.cpp | 458 ++++++++------ src/xlsx/xlsxstyles_p.h | 20 +- src/xlsx/xlsxtheme.cpp | 364 +++++------ src/xlsx/xlsxtheme_p.h | 1 - src/xlsx/xlsxutility.cpp | 87 +-- src/xlsx/xlsxutility_p.h | 12 +- src/xlsx/xlsxworkbook.cpp | 248 ++++---- src/xlsx/xlsxworkbook.h | 32 +- src/xlsx/xlsxworkbook_p.h | 27 +- src/xlsx/xlsxworksheet.cpp | 620 +++++++++++-------- src/xlsx/xlsxworksheet.h | 72 ++- src/xlsx/xlsxworksheet_p.h | 102 +-- src/xlsx/xlsxzipreader.cpp | 9 +- 88 files changed, 2527 insertions(+), 2040 deletions(-) create mode 100644 _clang-format diff --git a/_clang-format b/_clang-format new file mode 100644 index 0000000..6908972 --- /dev/null +++ b/_clang-format @@ -0,0 +1,25 @@ +BasedOnStyle: WebKit +Standard: Cpp11 +ColumnLimit: 100 +PointerBindsToType: false +BreakBeforeBinaryOperators: NonAssignment +BreakBeforeBraces: Custom +BraceWrapping: + AfterClass: true + AfterControlStatement: false + AfterEnum: false + AfterFunction: true + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: true + AfterUnion: false + BeforeCatch: false + BeforeElse: false + IndentBraces: false +AlignAfterOpenBracket: true +AlwaysBreakTemplateDeclarations: true +AllowShortFunctionsOnASingleLine: InlineOnly +NamespaceIndentation: None +SortIncludes: false +ForEachMacros: [ forever, foreach, Q_FOREACH, BOOST_FOREACH ] + diff --git a/examples/xlsx/calendar/main.cpp b/examples/xlsx/calendar/main.cpp index 3ad957e..db54797 100644 --- a/examples/xlsx/calendar/main.cpp +++ b/examples/xlsx/calendar/main.cpp @@ -10,16 +10,16 @@ int main(int argc, char **argv) { QCoreApplication app(argc, argv); - //Select a proper locale - //QLocale::setDefault(QLocale(QLocale::English)); + // Select a proper locale + // QLocale::setDefault(QLocale(QLocale::English)); Document xlsx; QDate today(QDate::currentDate()); - for (int month=1; month<=12; ++month) { + for (int month = 1; month <= 12; ++month) { xlsx.addSheet(QLocale().monthName(month)); xlsx.currentWorksheet()->setGridLinesVisible(false); - //the header row + // the header row Format headerStyle; headerStyle.setFontSize(48); headerStyle.setFontColor(Qt::darkBlue); @@ -29,8 +29,8 @@ int main(int argc, char **argv) xlsx.write("A1", QString("%1 %2").arg(QLocale().monthName(month)).arg(today.year())); xlsx.mergeCells("A1:N1", headerStyle); - //header with month titles - for (int day=1; day<=7; ++day) { + // header with month titles + for (int day = 1; day <= 7; ++day) { Format monthStyle; monthStyle.setFontSize(12); monthStyle.setFontColor(Qt::white); @@ -40,10 +40,10 @@ int main(int argc, char **argv) monthStyle.setFillPattern(Format::PatternSolid); monthStyle.setPatternBackgroundColor(Qt::darkBlue); - xlsx.setColumnWidth(day*2-1, day*2-1, 5); - xlsx.setColumnWidth(day*2, day*2, 13); - xlsx.write(2, day*2-1, QLocale().dayName(day)); - xlsx.mergeCells(CellRange(2, day*2-1, 2, day*2), monthStyle); + xlsx.setColumnWidth(day * 2 - 1, day * 2 - 1, 5); + xlsx.setColumnWidth(day * 2, day * 2, 13); + xlsx.write(2, day * 2 - 1, QLocale().dayName(day)); + xlsx.mergeCells(CellRange(2, day * 2 - 1, 2, day * 2), monthStyle); } QColor borderColor = QColor(Qt::gray); @@ -101,43 +101,42 @@ int main(int argc, char **argv) greyRightStyle.setBottomBorderColor(borderColor); int rownum = 3; - for (int day=1; day<=31; ++day) { + for (int day = 1; day <= 31; ++day) { QDate date(today.year(), month, day); if (!date.isValid()) break; xlsx.setRowHeight(rownum, 100); int dow = date.dayOfWeek(); - int colnum = dow*2-1; + int colnum = dow * 2 - 1; if (dow <= 5) { xlsx.write(rownum, colnum, day, workdayLeftStyle); - xlsx.write(rownum, colnum+1, QVariant(), workdayRightStyle); + xlsx.write(rownum, colnum + 1, QVariant(), workdayRightStyle); } else { xlsx.write(rownum, colnum, day, weekendLeftStyle); - xlsx.write(rownum, colnum+1, QVariant(), weekendRightStyle); + xlsx.write(rownum, colnum + 1, QVariant(), weekendRightStyle); } - if (day == 1 && dow != 1) {//First day - for (int i=1; isetChartType(Chart::CT_Scatter); - //Will generate three lines. + // Will generate three lines. scatterChart->addSeries(CellRange("A1:A9")); scatterChart->addSeries(CellRange("B1:B9")); scatterChart->addSeries(CellRange("C1:C9")); Chart *scatterChart_2 = xlsx.insertChart(83, 9, QSize(300, 300)); scatterChart_2->setChartType(Chart::CT_Scatter); - //Will generate two lines. + // Will generate two lines. scatterChart_2->addSeries(CellRange("A1:C9")); Chart *doughnutChart = xlsx.insertChart(103, 3, QSize(300, 300)); diff --git a/examples/xlsx/chartsheet/main.cpp b/examples/xlsx/chartsheet/main.cpp index c3e7a38..a70e0fa 100644 --- a/examples/xlsx/chartsheet/main.cpp +++ b/examples/xlsx/chartsheet/main.cpp @@ -10,13 +10,13 @@ int main() { //![0] Document xlsx; - for (int i=1; i<10; ++i) - xlsx.write(i, 1, i*i); + for (int i = 1; i < 10; ++i) + xlsx.write(i, 1, i * i); //![0] //![1] xlsx.addSheet("Chart1", AbstractSheet::ST_ChartSheet); - Chartsheet *sheet = static_cast(xlsx.currentSheet()); + Chartsheet *sheet = static_cast(xlsx.currentSheet()); Chart *barChart = sheet->chart(); barChart->setChartType(Chart::CT_Bar); barChart->addSeries(CellRange("A1:A9"), xlsx.sheet("Sheet1")); diff --git a/examples/xlsx/conditionalformatting/main.cpp b/examples/xlsx/conditionalformatting/main.cpp index 298238d..cf2804c 100644 --- a/examples/xlsx/conditionalformatting/main.cpp +++ b/examples/xlsx/conditionalformatting/main.cpp @@ -16,8 +16,8 @@ int main() xlsx.write("E1", "dataBar", hFmt); xlsx.write("F1", "colorScale", hFmt); - for (int row=3; row<22; ++row) { - for (int col=2; col<22; ++col) + for (int row = 3; row < 22; ++row) { + for (int col = 2; col < 22; ++col) xlsx.write(row, col, qrand() % 100); } //![0] diff --git a/examples/xlsx/definename/main.cpp b/examples/xlsx/definename/main.cpp index 9491eb2..3caaf7d 100644 --- a/examples/xlsx/definename/main.cpp +++ b/examples/xlsx/definename/main.cpp @@ -7,10 +7,10 @@ int main() { //![0] Document xlsx; - for (int i=1; i<=10; ++i) { + for (int i = 1; i <= 10; ++i) { xlsx.write(i, 1, i); - xlsx.write(i, 2, i*i); - xlsx.write(i, 3, i*i*i); + xlsx.write(i, 2, i * i); + xlsx.write(i, 3, i * i * i); } //![0] //![1] diff --git a/examples/xlsx/demo/main.cpp b/examples/xlsx/demo/main.cpp index 7d1e854..2586a09 100644 --- a/examples/xlsx/demo/main.cpp +++ b/examples/xlsx/demo/main.cpp @@ -6,53 +6,58 @@ QTXLSX_USE_NAMESPACE -void writeHorizontalAlignCell(Document &xlsx, const QString &cell, const QString &text, Format::HorizontalAlignment align) +void writeHorizontalAlignCell(Document &xlsx, const QString &cell, const QString &text, + Format::HorizontalAlignment align) { - Format format; - format.setHorizontalAlignment(align); - format.setBorderStyle(Format::BorderThin); - xlsx.write(cell, text, format); + Format format; + format.setHorizontalAlignment(align); + format.setBorderStyle(Format::BorderThin); + xlsx.write(cell, text, format); } -void writeVerticalAlignCell(Document &xlsx, const QString &range, const QString &text, Format::VerticalAlignment align) +void writeVerticalAlignCell(Document &xlsx, const QString &range, const QString &text, + Format::VerticalAlignment align) { - Format format; - format.setVerticalAlignment(align); - format.setBorderStyle(Format::BorderThin); - CellRange r(range); - xlsx.write(r.firstRow(), r.firstColumn(), text); - xlsx.mergeCells(r, format); + Format format; + format.setVerticalAlignment(align); + format.setBorderStyle(Format::BorderThin); + CellRange r(range); + xlsx.write(r.firstRow(), r.firstColumn(), text); + xlsx.mergeCells(r, format); } -void writeBorderStyleCell(Document &xlsx, const QString &cell, const QString &text, Format::BorderStyle bs) +void writeBorderStyleCell(Document &xlsx, const QString &cell, const QString &text, + Format::BorderStyle bs) { - Format format; - format.setBorderStyle(bs); - xlsx.write(cell, text, format); + Format format; + format.setBorderStyle(bs); + xlsx.write(cell, text, format); } void writeSolidFillCell(Document &xlsx, const QString &cell, const QColor &color) { - Format format; - format.setPatternBackgroundColor(color); - xlsx.write(cell, QVariant(), format); + Format format; + format.setPatternBackgroundColor(color); + xlsx.write(cell, QVariant(), format); } -void writePatternFillCell(Document &xlsx, const QString &cell, Format::FillPattern pattern, const QColor &color) +void writePatternFillCell(Document &xlsx, const QString &cell, Format::FillPattern pattern, + const QColor &color) { - Format format; - format.setPatternForegroundColor(color); - format.setFillPattern(pattern); - xlsx.write(cell, QVariant(), format); + Format format; + format.setPatternForegroundColor(color); + format.setFillPattern(pattern); + xlsx.write(cell, QVariant(), format); } -void writeBorderAndFontColorCell(Document &xlsx, const QString &cell, const QString &text, const QColor &color) +void writeBorderAndFontColorCell(Document &xlsx, const QString &cell, const QString &text, + const QColor &color) { - Format format; - format.setBorderStyle(Format::BorderThin); - format.setBorderColor(color); - format.setFontColor(color); - xlsx.write(cell, text, format); + Format format; + format.setBorderStyle(Format::BorderThin); + format.setBorderColor(color); + format.setFontColor(color); + xlsx.write(cell, text, format); } void writeFontNameCell(Document &xlsx, const QString &cell, const QString &text) @@ -93,13 +98,13 @@ int main() Document xlsx; //--------------------------------------------------------------- - //Create the first sheet (Otherwise, default "Sheet1" will be created) + // Create the first sheet (Otherwise, default "Sheet1" will be created) xlsx.addSheet("Aligns & Borders"); - xlsx.setColumnWidth(2, 20); //Column B - xlsx.setColumnWidth(8, 12); //Column H + xlsx.setColumnWidth(2, 20); // Column B + xlsx.setColumnWidth(8, 12); // Column H xlsx.currentWorksheet()->setGridLinesVisible(false); - //Alignment + // Alignment writeHorizontalAlignCell(xlsx, "B3", "AlignLeft", Format::AlignLeft); writeHorizontalAlignCell(xlsx, "B5", "AlignHCenter", Format::AlignHCenter); writeHorizontalAlignCell(xlsx, "B7", "AlignRight", Format::AlignRight); @@ -107,7 +112,7 @@ int main() writeVerticalAlignCell(xlsx, "F3:F7", "AlignVCenter", Format::AlignVCenter); writeVerticalAlignCell(xlsx, "H3:H7", "AlignBottom", Format::AlignBottom); - //Border + // Border writeBorderStyleCell(xlsx, "B13", "BorderMedium", Format::BorderMedium); writeBorderStyleCell(xlsx, "B15", "BorderDashed", Format::BorderDashed); writeBorderStyleCell(xlsx, "B17", "BorderDotted", Format::BorderDotted); @@ -115,7 +120,7 @@ int main() writeBorderStyleCell(xlsx, "B21", "BorderDouble", Format::BorderDouble); writeBorderStyleCell(xlsx, "B23", "BorderDashDot", Format::BorderDashDot); - //Fill + // Fill writeSolidFillCell(xlsx, "D13", Qt::red); writeSolidFillCell(xlsx, "D15", Qt::blue); writeSolidFillCell(xlsx, "D17", Qt::yellow); @@ -137,7 +142,7 @@ int main() writeBorderAndFontColorCell(xlsx, "H23", "Qt::gray", Qt::gray); //--------------------------------------------------------------- - //Create the second sheet. + // Create the second sheet. xlsx.addSheet("Fonts"); xlsx.write("B3", "Normal"); @@ -177,7 +182,7 @@ int main() xlsx.mergeCells("J3:J9"); //--------------------------------------------------------------- - //Create the third sheet. + // Create the third sheet. xlsx.addSheet("Formulas"); xlsx.setColumnWidth(1, 2, 40); Format rAlign; @@ -240,7 +245,7 @@ int main() xlsx.write("B33", "=HYPERLINK(\"http://qt-project.org\")", lAlign); //--------------------------------------------------------------- - //Create the fourth sheet. + // Create the fourth sheet. xlsx.addSheet("NumFormats"); xlsx.setColumnWidth(2, 40); writeInternalNumFormatsCell(xlsx, 4, 2.5681, 2); @@ -258,7 +263,7 @@ int main() writeCustomNumFormatsCell(xlsx, 16, 60, "[Red][<=100];[Green][>100]"); //--------------------------------------------------------------- - //Create the fifth sheet. + // Create the fifth sheet. xlsx.addSheet("Merging"); Format centerAlign; centerAlign.setHorizontalAlignment(Format::AlignHCenter); @@ -271,11 +276,11 @@ int main() xlsx.mergeCells("E8:F21", centerAlign); //--------------------------------------------------------------- - //Create the fifth sheet. + // Create the fifth sheet. xlsx.addSheet("Grouping"); qsrand(QDateTime::currentMSecsSinceEpoch()); - for (int row=2; row<31; ++row) { - for (int col=1; col<=10; ++col) + for (int row = 2; row < 31; ++row) { + for (int col = 1; col <= 10; ++col) xlsx.write(row, col, qrand() % 100); } xlsx.groupRows(4, 7); @@ -288,7 +293,7 @@ int main() xlsx.saveAs("Book1.xlsx"); - //Make sure that read/write works well. + // Make sure that read/write works well. Document xlsx2("Book1.xlsx"); xlsx2.saveAs("Book2.xlsx"); diff --git a/examples/xlsx/extractdata/main.cpp b/examples/xlsx/extractdata/main.cpp index 041aa5d..e9aaa8f 100644 --- a/examples/xlsx/extractdata/main.cpp +++ b/examples/xlsx/extractdata/main.cpp @@ -4,16 +4,16 @@ int main() { { - //Create a new .xlsx file. - QXlsx::Document xlsx; - xlsx.write("A1", "Hello Qt!"); - xlsx.write("A2", 12345); - xlsx.write("A3", "=44+33"); - xlsx.write("A4", true); - xlsx.write("A5", "http://qt-project.org"); - xlsx.write("A6", QDate(2013, 12, 27)); - xlsx.write("A7", QTime(6, 30)); - xlsx.saveAs("Book1.xlsx"); + // Create a new .xlsx file. + QXlsx::Document xlsx; + xlsx.write("A1", "Hello Qt!"); + xlsx.write("A2", 12345); + xlsx.write("A3", "=44+33"); + xlsx.write("A4", true); + xlsx.write("A5", "http://qt-project.org"); + xlsx.write("A6", QDate(2013, 12, 27)); + xlsx.write("A7", QTime(6, 30)); + xlsx.saveAs("Book1.xlsx"); } //![0] @@ -21,19 +21,19 @@ int main() //![0] //![1] - qDebug()<value(); + for (int row = 1; row < 10; ++row) { + if (QXlsx::Cell *cell = xlsx.cellAt(row, 1)) + qDebug() << cell->value(); } //![2] diff --git a/examples/xlsx/formulas/main.cpp b/examples/xlsx/formulas/main.cpp index c824af3..1a80377 100644 --- a/examples/xlsx/formulas/main.cpp +++ b/examples/xlsx/formulas/main.cpp @@ -54,24 +54,28 @@ int main() xlsx.addSheet("ArrayFormula"); Worksheet *sheet = xlsx.currentWorksheet(); - for (int row=2; row<20; ++row) { - sheet->write(row, 2, row*2); //B2:B19 - sheet->write(row, 3, row*3); //C2:C19 + for (int row = 2; row < 20; ++row) { + sheet->write(row, 2, row * 2); // B2:B19 + sheet->write(row, 3, row * 3); // C2:C19 } sheet->writeFormula("D2", CellFormula("B2:B19+C2:C19", "D2:D19", CellFormula::ArrayType)); - sheet->writeFormula("E2", CellFormula("=CONCATENATE(\"The total is \",D2:D19,\" units\")", "E2:E19", CellFormula::ArrayType)); + sheet->writeFormula("E2", + CellFormula("=CONCATENATE(\"The total is \",D2:D19,\" units\")", "E2:E19", + CellFormula::ArrayType)); //![2] //![21] xlsx.addSheet("SharedFormula"); sheet = xlsx.currentWorksheet(); - for (int row=2; row<20; ++row) { - sheet->write(row, 2, row*2); //B2:B19 - sheet->write(row, 3, row*3); //C2:C19 + for (int row = 2; row < 20; ++row) { + sheet->write(row, 2, row * 2); // B2:B19 + sheet->write(row, 3, row * 3); // C2:C19 } sheet->writeFormula("D2", CellFormula("=B2+C2", "D2:D19", CellFormula::SharedType)); - sheet->writeFormula("E2", CellFormula("=CONCATENATE(\"The total is \",D2,\" units\")", "E2:E19", CellFormula::SharedType)); + sheet->writeFormula("E2", + CellFormula("=CONCATENATE(\"The total is \",D2,\" units\")", "E2:E19", + CellFormula::SharedType)); //![21] @@ -79,11 +83,11 @@ int main() xlsx.save(); //![3] - //Make sure that read/write works well. + // Make sure that read/write works well. Document xlsx2("Book1.xlsx"); - Worksheet *sharedFormulaSheet = dynamic_cast(xlsx2.sheet("SharedFormula")); - for (int row=2; row<20; ++row) { - qDebug()<read(row, 4); + Worksheet *sharedFormulaSheet = dynamic_cast(xlsx2.sheet("SharedFormula")); + for (int row = 2; row < 20; ++row) { + qDebug() << sharedFormulaSheet->read(row, 4); } xlsx2.saveAs("Book2.xlsx"); diff --git a/examples/xlsx/image/main.cpp b/examples/xlsx/image/main.cpp index 7dcf9c4..363834b 100644 --- a/examples/xlsx/image/main.cpp +++ b/examples/xlsx/image/main.cpp @@ -1,15 +1,15 @@ #include #include "xlsxdocument.h" -int main(int argc, char** argv) +int main(int argc, char **argv) { QGuiApplication(argc, argv); QXlsx::Document xlsx; QImage image(40, 30, QImage::Format_RGB32); image.fill(Qt::green); - for (int i=0; i<10; ++i) - xlsx.insertImage(10*i, 5, image); + for (int i = 0; i < 10; ++i) + xlsx.insertImage(10 * i, 5, image); xlsx.saveAs("Book1.xlsx"); QXlsx::Document xlsx2("Book1.xlsx"); diff --git a/examples/xlsx/mergecells/main.cpp b/examples/xlsx/mergecells/main.cpp index 28e5e9d..5e1060f 100644 --- a/examples/xlsx/mergecells/main.cpp +++ b/examples/xlsx/mergecells/main.cpp @@ -23,4 +23,3 @@ int main() return 0; } - diff --git a/examples/xlsx/numberformat/main.cpp b/examples/xlsx/numberformat/main.cpp index 1fb4b9a..a76ece6 100644 --- a/examples/xlsx/numberformat/main.cpp +++ b/examples/xlsx/numberformat/main.cpp @@ -2,7 +2,7 @@ #include "xlsxdocument.h" #include "xlsxformat.h" -int main(int argc, char** argv) +int main(int argc, char **argv) { QGuiApplication(argc, argv); @@ -13,17 +13,17 @@ int main(int argc, char** argv) header.setFontBold(true); header.setFontSize(20); - //Custom number formats + // Custom number formats QStringList numFormats; - numFormats<<"Qt #" - <<"yyyy-mmm-dd" - <<"$ #,##0.00" - <<"[red]0.00"; + numFormats << "Qt #" + << "yyyy-mmm-dd" + << "$ #,##0.00" + << "[red]0.00"; xlsx.write(1, 1, "Raw data", header); xlsx.write(1, 2, "Format", header); xlsx.write(1, 3, "Shown value", header); - for (int i=0; i (C1)"); - //Set the height of the first row to 50.0(points) + // Set the height of the first row to 50.0(points) xlsx.setRowHeight(1, 50.0); - //Set the width of the third column to 40.0(chars) + // Set the width of the third column to 40.0(chars) xlsx.setColumnWidth(3, 3, 40.0); - //Set style for the row 11th. + // Set style for the row 11th. QXlsx::Format format1; format1.setFontBold(true); format1.setFontColor(QColor(Qt::blue)); @@ -23,13 +23,13 @@ int main() xlsx.setRowFormat(11, format1); xlsx.setRowHeight(11, 41); - //Set style for the col [9th, 16th) + // Set style for the col [9th, 16th) QXlsx::Format format2; format2.setFontBold(true); format2.setFontColor(QColor(Qt::magenta)); - for (int row=12; row<=30; row++) - for (int col=9; col<=15; col++) - xlsx.write(row, col, row+col); + for (int row = 12; row <= 30; row++) + for (int col = 9; col <= 15; col++) + xlsx.write(row, col, row + col); xlsx.setColumnWidth(9, 16, 5.0); xlsx.setColumnFormat(9, 16, format2); diff --git a/examples/xlsx/style/main.cpp b/examples/xlsx/style/main.cpp index ae99412..f1ec941 100644 --- a/examples/xlsx/style/main.cpp +++ b/examples/xlsx/style/main.cpp @@ -31,9 +31,9 @@ int main() QXlsx::Format format4; format4.setFontBold(true); format4.setFontColor(QColor(Qt::magenta)); - for (int row=21; row<=40; row++) - for (int col=9; col<16; col++) - xlsx.write(row, col, row+col); + for (int row = 21; row <= 40; row++) + for (int col = 9; col < 16; col++) + xlsx.write(row, col, row + col); xlsx.setColumnFormat(9, 16, format4); xlsx.write("A5", QDate(2013, 8, 29)); diff --git a/examples/xlsx/worksheetoperations/main.cpp b/examples/xlsx/worksheetoperations/main.cpp index d0c23a2..e5a95e1 100644 --- a/examples/xlsx/worksheetoperations/main.cpp +++ b/examples/xlsx/worksheetoperations/main.cpp @@ -9,8 +9,8 @@ int main() //![Create a xlsx file] Document xlsx; - for (int i=1; i<20; ++i) { - for (int j=1; j<15; ++j) + for (int i = 1; i < 20; ++i) { + for (int j = 1; j < 15; ++j) xlsx.write(i, j, QString("R %1 C %2").arg(i).arg(j)); } xlsx.addSheet(); @@ -26,7 +26,7 @@ int main() xlsx.sheet("VeryHiddenSheet")->setSheetState(AbstractSheet::SS_VeryHidden); xlsx.write("A1", "This sheet is very hidden."); - xlsx.save();//Default name is "Book1.xlsx" + xlsx.save(); // Default name is "Book1.xlsx" //![Create a xlsx file] Document xlsx2("Book1.xlsx"); diff --git a/examples/xlsx/xlsxwidget/main.cpp b/examples/xlsx/xlsxwidget/main.cpp index 845774a..517fbc8 100644 --- a/examples/xlsx/xlsxwidget/main.cpp +++ b/examples/xlsx/xlsxwidget/main.cpp @@ -30,7 +30,8 @@ int main(int argc, char **argv) QTableView *view = new QTableView(&tabWidget); view->setModel(new SheetModel(sheet, view)); foreach (CellRange range, sheet->mergedCells()) - view->setSpan(range.firstRow()-1, range.firstColumn()-1, range.rowCount(), range.columnCount()); + view->setSpan(range.firstRow() - 1, range.firstColumn() - 1, range.rowCount(), + range.columnCount()); tabWidget.addTab(view, sheetName); } } diff --git a/examples/xlsx/xlsxwidget/xlsxsheetmodel.cpp b/examples/xlsx/xlsxwidget/xlsxsheetmodel.cpp index d2142c6..4919002 100644 --- a/examples/xlsx/xlsxwidget/xlsxsheetmodel.cpp +++ b/examples/xlsx/xlsxwidget/xlsxsheetmodel.cpp @@ -32,9 +32,8 @@ QT_BEGIN_NAMESPACE_XLSX SheetModelPrivate::SheetModelPrivate(SheetModel *p) - :q_ptr(p) + : q_ptr(p) { - } /*! @@ -50,7 +49,8 @@ SheetModelPrivate::SheetModelPrivate(SheetModel *p) * Creates a model object with the given \a sheet and \a parent. */ SheetModel::SheetModel(Worksheet *sheet, QObject *parent) - :QAbstractTableModel(parent), d_ptr(new SheetModelPrivate(this)) + : QAbstractTableModel(parent) + , d_ptr(new SheetModelPrivate(this)) { d_ptr->sheet = sheet; } @@ -63,14 +63,13 @@ SheetModel::~SheetModel() delete d_ptr; } -int SheetModel::rowCount(const QModelIndex &/*parent*/) const +int SheetModel::rowCount(const QModelIndex & /*parent*/) const { Q_D(const SheetModel); return d->sheet->dimension().lastRow(); } - -int SheetModel::columnCount(const QModelIndex &/*parent*/) const +int SheetModel::columnCount(const QModelIndex & /*parent*/) const { Q_D(const SheetModel); return d->sheet->dimension().lastColumn(); @@ -90,10 +89,10 @@ QVariant SheetModel::data(const QModelIndex &index, int role) const if (!index.isValid()) return QVariant(); - Cell *cell = d->sheet->cellAt(index.row()+1, index.column()+1); + Cell *cell = d->sheet->cellAt(index.row() + 1, index.column() + 1); if (!cell) return QVariant(); - QVariant userFriendlyValue = d->sheet->read(index.row()+1, index.column()+1); + QVariant userFriendlyValue = d->sheet->read(index.row() + 1, index.column() + 1); if (role == Qt::DisplayRole) { if (cell->isDateTime()) @@ -160,7 +159,7 @@ static QString col_to_name(int col_num) remainder = col_num % 26; if (remainder == 0) remainder = 26; - col_str.prepend(QChar('A'+remainder-1)); + col_str.prepend(QChar('A' + remainder - 1)); col_num = (col_num - 1) / 26; } @@ -186,7 +185,7 @@ bool SheetModel::setData(const QModelIndex &index, const QVariant &value, int ro return false; if (role == Qt::EditRole) { - if (d->sheet->write(index.row()+1, index.column()+1, value) == 0) + if (d->sheet->write(index.row() + 1, index.column() + 1, value) == 0) return true; } diff --git a/examples/xlsx/xlsxwidget/xlsxsheetmodel.h b/examples/xlsx/xlsxwidget/xlsxsheetmodel.h index b500ff3..4da0f33 100644 --- a/examples/xlsx/xlsxwidget/xlsxsheetmodel.h +++ b/examples/xlsx/xlsxwidget/xlsxsheetmodel.h @@ -44,7 +44,7 @@ public: int rowCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const; - Qt::ItemFlags flags(const QModelIndex & index) const; + Qt::ItemFlags flags(const QModelIndex &index) const; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); @@ -55,7 +55,7 @@ signals: public slots: private: - SheetModelPrivate * const d_ptr; + SheetModelPrivate *const d_ptr; }; QT_END_NAMESPACE_XLSX diff --git a/src/xlsx/xlsxabstractooxmlfile.cpp b/src/xlsx/xlsxabstractooxmlfile.cpp index 36d15a0..93b93b7 100644 --- a/src/xlsx/xlsxabstractooxmlfile.cpp +++ b/src/xlsx/xlsxabstractooxmlfile.cpp @@ -31,15 +31,16 @@ QT_BEGIN_NAMESPACE_XLSX -AbstractOOXmlFilePrivate::AbstractOOXmlFilePrivate(AbstractOOXmlFile *q, AbstractOOXmlFile::CreateFlag flag=AbstractOOXmlFile::F_NewFromScratch) - :relationships(new Relationships), flag(flag), q_ptr(q) +AbstractOOXmlFilePrivate::AbstractOOXmlFilePrivate( + AbstractOOXmlFile *q, AbstractOOXmlFile::CreateFlag flag = AbstractOOXmlFile::F_NewFromScratch) + : relationships(new Relationships) + , flag(flag) + , q_ptr(q) { - } AbstractOOXmlFilePrivate::~AbstractOOXmlFilePrivate() { - } /*! @@ -51,14 +52,13 @@ AbstractOOXmlFilePrivate::~AbstractOOXmlFilePrivate() */ AbstractOOXmlFile::AbstractOOXmlFile(CreateFlag flag) - :d_ptr(new AbstractOOXmlFilePrivate(this, flag)) + : d_ptr(new AbstractOOXmlFilePrivate(this, flag)) { } AbstractOOXmlFile::AbstractOOXmlFile(AbstractOOXmlFilePrivate *d) - :d_ptr(d) + : d_ptr(d) { - } AbstractOOXmlFile::~AbstractOOXmlFile() @@ -105,7 +105,6 @@ QString AbstractOOXmlFile::filePath() const return d->filePathInPackage; } - /*! * \internal */ @@ -115,5 +114,4 @@ Relationships *AbstractOOXmlFile::relationships() const return d->relationships; } - QT_END_NAMESPACE_XLSX diff --git a/src/xlsx/xlsxabstractooxmlfile.h b/src/xlsx/xlsxabstractooxmlfile.h index a5a791c..5f0783a 100644 --- a/src/xlsx/xlsxabstractooxmlfile.h +++ b/src/xlsx/xlsxabstractooxmlfile.h @@ -39,11 +39,7 @@ class Q_XLSX_EXPORT AbstractOOXmlFile { Q_DECLARE_PRIVATE(AbstractOOXmlFile) public: - enum CreateFlag - { - F_NewFromScratch, - F_LoadFromExists - }; + enum CreateFlag { F_NewFromScratch, F_LoadFromExists }; virtual ~AbstractOOXmlFile(); diff --git a/src/xlsx/xlsxabstractooxmlfile_p.h b/src/xlsx/xlsxabstractooxmlfile_p.h index a1a2e60..30ad83e 100644 --- a/src/xlsx/xlsxabstractooxmlfile_p.h +++ b/src/xlsx/xlsxabstractooxmlfile_p.h @@ -52,8 +52,8 @@ public: AbstractOOXmlFilePrivate(AbstractOOXmlFile *q, AbstractOOXmlFile::CreateFlag flag); virtual ~AbstractOOXmlFilePrivate(); - QString filePathInPackage;//such as "xl/worksheets/sheet1.xml" - //used when load the .xlsx file + QString filePathInPackage; // such as "xl/worksheets/sheet1.xml" + // used when load the .xlsx file Relationships *relationships; AbstractOOXmlFile::CreateFlag flag; AbstractOOXmlFile *q_ptr; diff --git a/src/xlsx/xlsxabstractsheet.cpp b/src/xlsx/xlsxabstractsheet.cpp index 2cf6eee..6b0d865 100644 --- a/src/xlsx/xlsxabstractsheet.cpp +++ b/src/xlsx/xlsxabstractsheet.cpp @@ -72,15 +72,15 @@ AbstractSheetPrivate::~AbstractSheetPrivate() /*! * \internal */ -AbstractSheet::AbstractSheet(const QString &name, int id, Workbook *workbook, AbstractSheetPrivate *d) : - AbstractOOXmlFile(d) +AbstractSheet::AbstractSheet(const QString &name, int id, Workbook *workbook, + AbstractSheetPrivate *d) + : AbstractOOXmlFile(d) { d_func()->name = name; d_func()->id = id; d_func()->workbook = workbook; } - /*! * Returns the name of the sheet. */ diff --git a/src/xlsx/xlsxabstractsheet.h b/src/xlsx/xlsxabstractsheet.h index 7aa416d..08e56ff 100644 --- a/src/xlsx/xlsxabstractsheet.h +++ b/src/xlsx/xlsxabstractsheet.h @@ -37,18 +37,9 @@ class Q_XLSX_EXPORT AbstractSheet : public AbstractOOXmlFile { Q_DECLARE_PRIVATE(AbstractSheet) public: - enum SheetType { - ST_WorkSheet, - ST_ChartSheet, - ST_DialogSheet, - ST_MacroSheet - }; + enum SheetType { ST_WorkSheet, ST_ChartSheet, ST_DialogSheet, ST_MacroSheet }; - enum SheetState { - SS_Visible, - SS_Hidden, - SS_VeryHidden - }; + enum SheetState { SS_Visible, SS_Hidden, SS_VeryHidden }; QString sheetName() const; SheetType sheetType() const; diff --git a/src/xlsx/xlsxabstractsheet_p.h b/src/xlsx/xlsxabstractsheet_p.h index 7d0f344..64a84ac 100644 --- a/src/xlsx/xlsxabstractsheet_p.h +++ b/src/xlsx/xlsxabstractsheet_p.h @@ -59,6 +59,5 @@ public: AbstractSheet::SheetState sheetState; AbstractSheet::SheetType type; }; - } #endif // XLSXABSTRACTSHEET_P_H diff --git a/src/xlsx/xlsxcell.cpp b/src/xlsx/xlsxcell.cpp index fcaf7a6..a3938a3 100644 --- a/src/xlsx/xlsxcell.cpp +++ b/src/xlsx/xlsxcell.cpp @@ -33,17 +33,19 @@ QT_BEGIN_NAMESPACE_XLSX -CellPrivate::CellPrivate(Cell *p) : - q_ptr(p) +CellPrivate::CellPrivate(Cell *p) + : q_ptr(p) { - } -CellPrivate::CellPrivate(const CellPrivate * const cp) - : value(cp->value), formula(cp->formula), cellType(cp->cellType) - , format(cp->format), richString(cp->richString), parent(cp->parent) +CellPrivate::CellPrivate(const CellPrivate *const cp) + : value(cp->value) + , formula(cp->formula) + , cellType(cp->cellType) + , format(cp->format) + , richString(cp->richString) + , parent(cp->parent) { - } /*! @@ -67,8 +69,8 @@ CellPrivate::CellPrivate(const CellPrivate * const cp) * \internal * Created by Worksheet only. */ -Cell::Cell(const QVariant &data, CellType type, const Format &format, Worksheet *parent) : - d_ptr(new CellPrivate(this)) +Cell::Cell(const QVariant &data, CellType type, const Format &format, Worksheet *parent) + : d_ptr(new CellPrivate(this)) { d_ptr->value = data; d_ptr->cellType = type; @@ -79,8 +81,8 @@ Cell::Cell(const QVariant &data, CellType type, const Format &format, Worksheet /*! * \internal */ -Cell::Cell(const Cell * const cell): - d_ptr(new CellPrivate(cell->d_ptr)) +Cell::Cell(const Cell *const cell) + : d_ptr(new CellPrivate(cell->d_ptr)) { d_ptr->q_ptr = this; } @@ -144,8 +146,8 @@ CellFormula Cell::formula() const bool Cell::isDateTime() const { Q_D(const Cell); - if (d->cellType == NumberType && d->value.toDouble() >=0 - && d->format.isValid() && d->format.isDateTimeFormat()) { + if (d->cellType == NumberType && d->value.toDouble() >= 0 && d->format.isValid() + && d->format.isDateTimeFormat()) { return true; } return false; @@ -169,7 +171,7 @@ bool Cell::isRichString() const { Q_D(const Cell); if (d->cellType != SharedStringType && d->cellType != InlineStringType - && d->cellType != StringType) + && d->cellType != StringType) return false; return d->richString.isRichString(); diff --git a/src/xlsx/xlsxcell.h b/src/xlsx/xlsxcell.h index 7aec8ce..0095687 100644 --- a/src/xlsx/xlsxcell.h +++ b/src/xlsx/xlsxcell.h @@ -42,12 +42,12 @@ class Q_XLSX_EXPORT Cell Q_DECLARE_PRIVATE(Cell) public: enum CellType { - BooleanType, //t="b" - NumberType, //t="n" (default) - ErrorType, //t="e" - SharedStringType, //t="s" - StringType, //t="str" - InlineStringType //t="inlineStr" + BooleanType, // t="b" + NumberType, // t="n" (default) + ErrorType, // t="e" + SharedStringType, // t="s" + StringType, // t="str" + InlineStringType // t="inlineStr" }; CellType cellType() const; @@ -63,13 +63,15 @@ public: bool isRichString() const; ~Cell(); + private: friend class Worksheet; friend class WorksheetPrivate; - Cell(const QVariant &data=QVariant(), CellType type=NumberType, const Format &format=Format(), Worksheet *parent=0); - Cell(const Cell * const cell); - CellPrivate * const d_ptr; + Cell(const QVariant &data = QVariant(), CellType type = NumberType, + const Format &format = Format(), Worksheet *parent = 0); + Cell(const Cell *const cell); + CellPrivate *const d_ptr; }; QT_END_NAMESPACE_XLSX diff --git a/src/xlsx/xlsxcell_p.h b/src/xlsx/xlsxcell_p.h index b537ff2..9f271e5 100644 --- a/src/xlsx/xlsxcell_p.h +++ b/src/xlsx/xlsxcell_p.h @@ -51,7 +51,7 @@ class CellPrivate Q_DECLARE_PUBLIC(Cell) public: CellPrivate(Cell *p); - CellPrivate(const CellPrivate * const cp); + CellPrivate(const CellPrivate *const cp); QVariant value; CellFormula formula; diff --git a/src/xlsx/xlsxcellformula.cpp b/src/xlsx/xlsxcellformula.cpp index 858d347..256ec2e 100644 --- a/src/xlsx/xlsxcellformula.cpp +++ b/src/xlsx/xlsxcellformula.cpp @@ -31,27 +31,33 @@ QT_BEGIN_NAMESPACE_XLSX -CellFormulaPrivate::CellFormulaPrivate(const QString &formula_, const CellRange &ref_, CellFormula::FormulaType type_) - :formula(formula_), type(type_), reference(ref_), ca(false), si(0) +CellFormulaPrivate::CellFormulaPrivate(const QString &formula_, const CellRange &ref_, + CellFormula::FormulaType type_) + : formula(formula_) + , type(type_) + , reference(ref_) + , ca(false) + , si(0) { - //Remove the formula '=' sign if exists + // Remove the formula '=' sign if exists if (formula.startsWith(QLatin1String("="))) - formula.remove(0,1); + formula.remove(0, 1); else if (formula.startsWith(QLatin1String("{=")) && formula.endsWith(QLatin1String("}"))) - formula = formula.mid(2, formula.length()-3); + formula = formula.mid(2, formula.length() - 3); } CellFormulaPrivate::CellFormulaPrivate(const CellFormulaPrivate &other) : QSharedData(other) - , formula(other.formula), type(other.type), reference(other.reference) - , ca(other.ca), si(other.si) + , formula(other.formula) + , type(other.type) + , reference(other.reference) + , ca(other.ca) + , si(other.si) { - } CellFormulaPrivate::~CellFormulaPrivate() { - } /*! @@ -74,41 +80,38 @@ CellFormulaPrivate::~CellFormulaPrivate() */ CellFormula::CellFormula() { - //The d pointer is initialized with a null pointer + // The d pointer is initialized with a null pointer } /*! * Creates a new formula with the given \a formula and \a type. */ CellFormula::CellFormula(const char *formula, FormulaType type) - :d(new CellFormulaPrivate(QString::fromLatin1(formula), CellRange(), type)) + : d(new CellFormulaPrivate(QString::fromLatin1(formula), CellRange(), type)) { - } /*! * Creates a new formula with the given \a formula and \a type. */ CellFormula::CellFormula(const QString &formula, FormulaType type) - :d(new CellFormulaPrivate(formula, CellRange(), type)) + : d(new CellFormulaPrivate(formula, CellRange(), type)) { - } /*! * Creates a new formula with the given \a formula, \a ref and \a type. */ CellFormula::CellFormula(const QString &formula, const CellRange &ref, FormulaType type) - :d(new CellFormulaPrivate(formula, ref, type)) + : d(new CellFormulaPrivate(formula, ref, type)) { - } /*! Creates a new formula with the same attributes as the \a other formula. */ CellFormula::CellFormula(const CellFormula &other) - :d(other.d) + : d(other.d) { } @@ -116,7 +119,7 @@ CellFormula::CellFormula(const CellFormula &other) Assigns the \a other formula to this formula, and returns a reference to this formula. */ -CellFormula &CellFormula::operator =(const CellFormula &other) +CellFormula &CellFormula::operator=(const CellFormula &other) { d = other.d; return *this; @@ -127,7 +130,6 @@ CellFormula &CellFormula::operator =(const CellFormula &other) */ CellFormula::~CellFormula() { - } /*! @@ -200,7 +202,7 @@ bool CellFormula::saveToXml(QXmlStreamWriter &writer) const if (!d->formula.isEmpty()) writer.writeCharacters(d->formula); - writer.writeEndElement(); //f + writer.writeEndElement(); // f return true; } @@ -241,19 +243,17 @@ bool CellFormula::loadFromXml(QXmlStreamReader &reader) /*! * \internal */ -bool CellFormula::operator ==(const CellFormula &formula) const +bool CellFormula::operator==(const CellFormula &formula) const { - return d->formula == formula.d->formula && d->type == formula.d->type - && d->si ==formula.d->si; + return d->formula == formula.d->formula && d->type == formula.d->type && d->si == formula.d->si; } /*! * \internal */ -bool CellFormula::operator !=(const CellFormula &formula) const +bool CellFormula::operator!=(const CellFormula &formula) const { - return d->formula != formula.d->formula || d->type != formula.d->type - || d->si !=formula.d->si; + return d->formula != formula.d->formula || d->type != formula.d->type || d->si != formula.d->si; } QT_END_NAMESPACE_XLSX diff --git a/src/xlsx/xlsxcellformula.h b/src/xlsx/xlsxcellformula.h index 0d4679b..14eeacb 100644 --- a/src/xlsx/xlsxcellformula.h +++ b/src/xlsx/xlsxcellformula.h @@ -41,20 +41,15 @@ class WorksheetPrivate; class Q_XLSX_EXPORT CellFormula { public: - enum FormulaType { - NormalType, - ArrayType, - DataTableType, - SharedType - }; + enum FormulaType { NormalType, ArrayType, DataTableType, SharedType }; CellFormula(); - CellFormula(const char *formula, FormulaType type=NormalType); - CellFormula(const QString &formula, FormulaType type=NormalType); + CellFormula(const char *formula, FormulaType type = NormalType); + CellFormula(const QString &formula, FormulaType type = NormalType); CellFormula(const QString &formula, const CellRange &ref, FormulaType type); CellFormula(const CellFormula &other); ~CellFormula(); - CellFormula &operator =(const CellFormula &other); + CellFormula &operator=(const CellFormula &other); bool isValid() const; FormulaType formulaType() const; @@ -62,11 +57,12 @@ public: CellRange reference() const; int sharedIndex() const; - bool operator == (const CellFormula &formula) const; - bool operator != (const CellFormula &formula) const; + bool operator==(const CellFormula &formula) const; + bool operator!=(const CellFormula &formula) const; bool saveToXml(QXmlStreamWriter &writer) const; bool loadFromXml(QXmlStreamReader &reader); + private: friend class Worksheet; friend class WorksheetPrivate; diff --git a/src/xlsx/xlsxcellformula_p.h b/src/xlsx/xlsxcellformula_p.h index 6aeddc9..ac8a130 100644 --- a/src/xlsx/xlsxcellformula_p.h +++ b/src/xlsx/xlsxcellformula_p.h @@ -48,15 +48,16 @@ QT_BEGIN_NAMESPACE_XLSX class CellFormulaPrivate : public QSharedData { public: - CellFormulaPrivate(const QString &formula, const CellRange &reference, CellFormula::FormulaType type); + CellFormulaPrivate(const QString &formula, const CellRange &reference, + CellFormula::FormulaType type); CellFormulaPrivate(const CellFormulaPrivate &other); ~CellFormulaPrivate(); - QString formula; //formula contents + QString formula; // formula contents CellFormula::FormulaType type; CellRange reference; - bool ca; //Calculate Cell - int si; //Shared group index + bool ca; // Calculate Cell + int si; // Shared group index }; QT_END_NAMESPACE_XLSX diff --git a/src/xlsx/xlsxcellrange.cpp b/src/xlsx/xlsxcellrange.cpp index 6251ab7..9126f9f 100644 --- a/src/xlsx/xlsxcellrange.cpp +++ b/src/xlsx/xlsxcellrange.cpp @@ -44,7 +44,10 @@ QT_BEGIN_NAMESPACE_XLSX whose rowCount() and columnCount() are 0. */ CellRange::CellRange() - : top(-1), left(-1), bottom(-2), right(-2) + : top(-1) + , left(-1) + , bottom(-2) + , right(-2) { } @@ -55,13 +58,18 @@ CellRange::CellRange() \sa topRow(), leftColumn(), bottomRow(), rightColumn() */ CellRange::CellRange(int top, int left, int bottom, int right) - : top(top), left(left), bottom(bottom), right(right) + : top(top) + , left(left) + , bottom(bottom) + , right(right) { } CellRange::CellRange(const CellReference &topLeft, const CellReference &bottomRight) - : top(topLeft.row()), left(topLeft.column()) - , bottom(bottomRight.row()), right(bottomRight.column()) + : top(topLeft.row()) + , left(topLeft.column()) + , bottom(bottomRight.row()) + , right(bottomRight.column()) { } @@ -107,7 +115,10 @@ void CellRange::init(const QString &range) other range. */ CellRange::CellRange(const CellRange &other) - : top(other.top), left(other.left), bottom(other.bottom), right(other.right) + : top(other.top) + , left(other.left) + , bottom(other.bottom) + , right(other.right) { } @@ -127,7 +138,7 @@ QString CellRange::toString(bool row_abs, bool col_abs) const return QString(); if (left == right && top == bottom) { - //Single cell + // Single cell return CellReference(top, left).toString(row_abs, col_abs); } diff --git a/src/xlsx/xlsxcellrange.h b/src/xlsx/xlsxcellrange.h index 5a510b0..1d110f6 100644 --- a/src/xlsx/xlsxcellrange.h +++ b/src/xlsx/xlsxcellrange.h @@ -40,7 +40,7 @@ public: CellRange(const CellRange &other); ~CellRange(); - QString toString(bool row_abs=false, bool col_abs=false) const; + QString toString(bool row_abs = false, bool col_abs = false) const; bool isValid() const; inline void setFirstRow(int row) { top = row; } inline void setLastRow(int row) { bottom = row; } @@ -57,16 +57,17 @@ public: inline CellReference bottomLeft() const { return CellReference(bottom, left); } inline CellReference bottomRight() const { return CellReference(bottom, right); } - inline bool operator ==(const CellRange &other) const + inline bool operator==(const CellRange &other) const { - return top==other.top && bottom==other.bottom - && left == other.left && right == other.right; + return top == other.top && bottom == other.bottom && left == other.left + && right == other.right; } - inline bool operator !=(const CellRange &other) const + inline bool operator!=(const CellRange &other) const { - return top!=other.top || bottom!=other.bottom - || left != other.left || right != other.right; + return top != other.top || bottom != other.bottom || left != other.left + || right != other.right; } + private: void init(const QString &range); int top, left, bottom, right; diff --git a/src/xlsx/xlsxcellreference.cpp b/src/xlsx/xlsxcellreference.cpp index e7cf5da..849a821 100644 --- a/src/xlsx/xlsxcellreference.cpp +++ b/src/xlsx/xlsxcellreference.cpp @@ -33,12 +33,16 @@ namespace { int intPow(int x, int p) { - if (p == 0) return 1; - if (p == 1) return x; + if (p == 0) + return 1; + if (p == 1) + return x; - int tmp = intPow(x, p/2); - if (p%2 == 0) return tmp * tmp; - else return x * tmp * tmp; + int tmp = intPow(x, p / 2); + if (p % 2 == 0) + return tmp * tmp; + else + return x * tmp * tmp; } QString col_to_name(int col_num) @@ -52,7 +56,7 @@ QString col_to_name(int col_num) remainder = col_num % 26; if (remainder == 0) remainder = 26; - col_str.prepend(QChar('A'+remainder-1)); + col_str.prepend(QChar('A' + remainder - 1)); col_num = (col_num - 1) / 26; } col_cache.insert(col_num, col_str); @@ -65,14 +69,14 @@ int col_from_name(const QString &col_str) { int col = 0; int expn = 0; - for (int i=col_str.size()-1; i>-1; --i) { + for (int i = col_str.size() - 1; i > -1; --i) { col += (col_str[i].unicode() - 'A' + 1) * intPow(26, expn); expn++; } return col; } -} //namespace +} // namespace /*! \class CellReference @@ -86,7 +90,8 @@ int col_from_name(const QString &col_str) Constructs an invalid Cell Reference */ CellReference::CellReference() - : _row(-1), _column(-1) + : _row(-1) + , _column(-1) { } @@ -94,7 +99,8 @@ CellReference::CellReference() Constructs the Reference from the given \a row, and \a column. */ CellReference::CellReference(int row, int column) - : _row(row), _column(column) + : _row(row) + , _column(column) { } @@ -133,7 +139,8 @@ void CellReference::init(const QString &cell_str) other Reference. */ CellReference::CellReference(const CellReference &other) - : _row(other._row), _column(other._column) + : _row(other._row) + , _column(other._column) { } diff --git a/src/xlsx/xlsxcellreference.h b/src/xlsx/xlsxcellreference.h index 6a917c2..978210e 100644 --- a/src/xlsx/xlsxcellreference.h +++ b/src/xlsx/xlsxcellreference.h @@ -38,7 +38,7 @@ public: CellReference(const CellReference &other); ~CellReference(); - QString toString(bool row_abs=false, bool col_abs=false) const; + QString toString(bool row_abs = false, bool col_abs = false) const; static CellReference fromString(const QString &cell); bool isValid() const; inline void setRow(int row) { _row = row; } @@ -46,14 +46,15 @@ public: inline int row() const { return _row; } inline int column() const { return _column; } - inline bool operator ==(const CellReference &other) const + inline bool operator==(const CellReference &other) const { - return _row==other._row && _column==other._column; + return _row == other._row && _column == other._column; } - inline bool operator !=(const CellReference &other) const + inline bool operator!=(const CellReference &other) const { - return _row!=other._row || _column!=other._column; + return _row != other._row || _column != other._column; } + private: void init(const QString &cell); int _row, _column; diff --git a/src/xlsx/xlsxchart.cpp b/src/xlsx/xlsxchart.cpp index a69f5c2..89a51aa 100644 --- a/src/xlsx/xlsxchart.cpp +++ b/src/xlsx/xlsxchart.cpp @@ -36,14 +36,13 @@ QT_BEGIN_NAMESPACE_XLSX ChartPrivate::ChartPrivate(Chart *q, Chart::CreateFlag flag) - :AbstractOOXmlFilePrivate(q, flag), chartType(static_cast(0)) + : AbstractOOXmlFilePrivate(q, flag) + , chartType(static_cast(0)) { - } ChartPrivate::~ChartPrivate() { - } /*! @@ -78,7 +77,7 @@ ChartPrivate::~ChartPrivate() * \internal */ Chart::Chart(AbstractSheet *parent, CreateFlag flag) - :AbstractOOXmlFile(new ChartPrivate(this, flag)) + : AbstractOOXmlFile(new ChartPrivate(this, flag)) { d_func()->sheet = parent; } @@ -104,46 +103,51 @@ void Chart::addSeries(const CellRange &range, AbstractSheet *sheet) return; QString sheetName = sheet ? sheet->sheetName() : d->sheet->sheetName(); - //In case sheetName contains space or ' + // In case sheetName contains space or ' sheetName = escapeSheetName(sheetName); if (range.columnCount() == 1 || range.rowCount() == 1) { QSharedPointer series = QSharedPointer(new XlsxSeries); - series->numberDataSource_numRef = sheetName + QLatin1String("!") + range.toString(true, true); + series->numberDataSource_numRef = + sheetName + QLatin1String("!") + range.toString(true, true); d->seriesList.append(series); } else if (range.columnCount() < range.rowCount()) { - //Column based series + // Column based series int firstDataColumn = range.firstColumn(); QString axDataSouruce_numRef; if (d->chartType == CT_Scatter || d->chartType == CT_Bubble) { firstDataColumn += 1; - CellRange subRange(range.firstRow(), range.firstColumn(), range.lastRow(), range.firstColumn()); + CellRange subRange(range.firstRow(), range.firstColumn(), range.lastRow(), + range.firstColumn()); axDataSouruce_numRef = sheetName + QLatin1String("!") + subRange.toString(true, true); } - for (int col=firstDataColumn; col<=range.lastColumn(); ++col) { + for (int col = firstDataColumn; col <= range.lastColumn(); ++col) { CellRange subRange(range.firstRow(), col, range.lastRow(), col); QSharedPointer series = QSharedPointer(new XlsxSeries); series->axDataSource_numRef = axDataSouruce_numRef; - series->numberDataSource_numRef = sheetName + QLatin1String("!") + subRange.toString(true, true); + series->numberDataSource_numRef = + sheetName + QLatin1String("!") + subRange.toString(true, true); d->seriesList.append(series); } } else { - //Row based series + // Row based series int firstDataRow = range.firstRow(); QString axDataSouruce_numRef; if (d->chartType == CT_Scatter || d->chartType == CT_Bubble) { firstDataRow += 1; - CellRange subRange(range.firstRow(), range.firstColumn(), range.firstRow(), range.lastColumn()); + CellRange subRange(range.firstRow(), range.firstColumn(), range.firstRow(), + range.lastColumn()); axDataSouruce_numRef = sheetName + QLatin1String("!") + subRange.toString(true, true); } - for (int row=firstDataRow; row<=range.lastRow(); ++row) { + for (int row = firstDataRow; row <= range.lastRow(); ++row) { CellRange subRange(row, range.firstColumn(), row, range.lastColumn()); QSharedPointer series = QSharedPointer(new XlsxSeries); series->axDataSource_numRef = axDataSouruce_numRef; - series->numberDataSource_numRef = sheetName + QLatin1String("!") + subRange.toString(true, true); + series->numberDataSource_numRef = + sheetName + QLatin1String("!") + subRange.toString(true, true); d->seriesList.append(series); } } @@ -165,7 +169,7 @@ void Chart::setChartType(ChartType type) void Chart::setChartStyle(int id) { Q_UNUSED(id) - //!Todo + //! Todo } /*! @@ -179,13 +183,17 @@ void Chart::saveToXmlFile(QIODevice *device) const writer.writeStartDocument(QStringLiteral("1.0"), true); writer.writeStartElement(QStringLiteral("c:chartSpace")); - writer.writeAttribute(QStringLiteral("xmlns:c"), QStringLiteral("http://schemas.openxmlformats.org/drawingml/2006/chart")); - writer.writeAttribute(QStringLiteral("xmlns:a"), QStringLiteral("http://schemas.openxmlformats.org/drawingml/2006/main")); - writer.writeAttribute(QStringLiteral("xmlns:r"), QStringLiteral("http://schemas.openxmlformats.org/officeDocument/2006/relationships")); + writer.writeAttribute(QStringLiteral("xmlns:c"), + QStringLiteral("http://schemas.openxmlformats.org/drawingml/2006/chart")); + writer.writeAttribute(QStringLiteral("xmlns:a"), + QStringLiteral("http://schemas.openxmlformats.org/drawingml/2006/main")); + writer.writeAttribute( + QStringLiteral("xmlns:r"), + QStringLiteral("http://schemas.openxmlformats.org/officeDocument/2006/relationships")); d->saveXmlChart(writer); - writer.writeEndElement();//c:chartSpace + writer.writeEndElement(); // c:chartSpace writer.writeEndDocument(); } @@ -220,10 +228,10 @@ bool ChartPrivate::loadXmlChart(QXmlStreamReader &reader) if (!loadXmlPlotArea(reader)) return false; } else if (reader.name() == QLatin1String("legend")) { - //!Todo + //! Todo } - } else if (reader.tokenType() == QXmlStreamReader::EndElement && - reader.name() == QLatin1String("chart")) { + } else if (reader.tokenType() == QXmlStreamReader::EndElement + && reader.name() == QLatin1String("chart")) { break; } } @@ -238,17 +246,17 @@ bool ChartPrivate::loadXmlPlotArea(QXmlStreamReader &reader) reader.readNextStartElement(); if (reader.tokenType() == QXmlStreamReader::StartElement) { if (reader.name() == QLatin1String("layout")) { - //!ToDo + //! ToDo } else if (reader.name().endsWith(QLatin1String("Chart"))) { - //For pieChart, barChart, ... + // For pieChart, barChart, ... loadXmlXxxChart(reader); } else if (reader.name().endsWith(QLatin1String("Ax"))) { - //For valAx, catAx, serAx, dateAx + // For valAx, catAx, serAx, dateAx loadXmlAxis(reader); } - } else if (reader.tokenType() == QXmlStreamReader::EndElement && - reader.name() == QLatin1String("plotArea")) { + } else if (reader.tokenType() == QXmlStreamReader::EndElement + && reader.name() == QLatin1String("plotArea")) { break; } } @@ -258,17 +266,28 @@ bool ChartPrivate::loadXmlPlotArea(QXmlStreamReader &reader) bool ChartPrivate::loadXmlXxxChart(QXmlStreamReader &reader) { QStringRef name = reader.name(); - if (name == QLatin1String("pieChart")) chartType = Chart::CT_Pie; - else if (name == QLatin1String("pie3DChart")) chartType = Chart::CT_Pie3D; - else if (name == QLatin1String("barChart")) chartType = Chart::CT_Bar; - else if (name == QLatin1String("bar3DChart")) chartType = Chart::CT_Bar3D; - else if (name == QLatin1String("lineChart")) chartType = Chart::CT_Line; - else if (name == QLatin1String("line3DChart")) chartType = Chart::CT_Line3D; - else if (name == QLatin1String("scatterChart")) chartType = Chart::CT_Scatter; - else if (name == QLatin1String("areaChart")) chartType = Chart::CT_Area; - else if (name == QLatin1String("area3DChart")) chartType = Chart::CT_Area3D; - else if (name == QLatin1String("doughnutChart")) chartType = Chart::CT_Doughnut; - else qDebug()<<"Cann't load chart: "< series = QSharedPointer(new XlsxSeries); seriesList.append(series); - while (!reader.atEnd() && !(reader.tokenType() == QXmlStreamReader::EndElement - && reader.name() == QLatin1String("ser"))) { + while (!reader.atEnd() + && !(reader.tokenType() == QXmlStreamReader::EndElement + && reader.name() == QLatin1String("ser"))) { if (reader.readNextStartElement()) { QStringRef name = reader.name(); if (name == QLatin1String("cat") || name == QLatin1String("xVal")) { - while (!reader.atEnd() && !(reader.tokenType() == QXmlStreamReader::EndElement - && reader.name() == name)) { + while (!reader.atEnd() + && !(reader.tokenType() == QXmlStreamReader::EndElement + && reader.name() == name)) { if (reader.readNextStartElement()) { if (reader.name() == QLatin1String("numRef")) series->axDataSource_numRef = loadXmlNumRef(reader); } } } else if (name == QLatin1String("val") || name == QLatin1String("yVal")) { - while (!reader.atEnd() && !(reader.tokenType() == QXmlStreamReader::EndElement - && reader.name() == name)) { + while (!reader.atEnd() + && !(reader.tokenType() == QXmlStreamReader::EndElement + && reader.name() == name)) { if (reader.readNextStartElement()) { if (reader.name() == QLatin1String("numRef")) series->numberDataSource_numRef = loadXmlNumRef(reader); } } } else if (name == QLatin1String("extLst")) { - while (!reader.atEnd() && !(reader.tokenType() == QXmlStreamReader::EndElement - && reader.name() == name)) { + while (!reader.atEnd() + && !(reader.tokenType() == QXmlStreamReader::EndElement + && reader.name() == name)) { reader.readNextStartElement(); } } @@ -325,13 +346,13 @@ bool ChartPrivate::loadXmlSer(QXmlStreamReader &reader) return true; } - QString ChartPrivate::loadXmlNumRef(QXmlStreamReader &reader) { Q_ASSERT(reader.name() == QLatin1String("numRef")); - while (!reader.atEnd() && !(reader.tokenType() == QXmlStreamReader::EndElement - && reader.name() == QLatin1String("numRef"))) { + while (!reader.atEnd() + && !(reader.tokenType() == QXmlStreamReader::EndElement + && reader.name() == QLatin1String("numRef"))) { if (reader.readNextStartElement()) { if (reader.name() == QLatin1String("f")) return reader.readElementText(); @@ -372,84 +393,93 @@ void ChartPrivate::saveXmlChart(QXmlStreamWriter &writer) const break; } saveXmlAxes(writer); - writer.writeEndElement(); //plotArea + writer.writeEndElement(); // plotArea -// saveXmlLegend(writer); + // saveXmlLegend(writer); - writer.writeEndElement(); //chart + writer.writeEndElement(); // chart } void ChartPrivate::saveXmlPieChart(QXmlStreamWriter &writer) const { - QString name = chartType==Chart::CT_Pie ? QStringLiteral("c:pieChart") : QStringLiteral("c:pie3DChart"); + QString name = + chartType == Chart::CT_Pie ? QStringLiteral("c:pieChart") : QStringLiteral("c:pie3DChart"); writer.writeStartElement(name); - //Do the same behavior as Excel, Pie prefer varyColors + // Do the same behavior as Excel, Pie prefer varyColors writer.writeEmptyElement(QStringLiteral("c:varyColors")); writer.writeAttribute(QStringLiteral("val"), QStringLiteral("1")); - for (int i=0; i(this)->axisList.append(QSharedPointer(new XlsxAxis(XlsxAxis::T_Cat, XlsxAxis::Bottom, 0, 1))); - const_cast(this)->axisList.append(QSharedPointer(new XlsxAxis(XlsxAxis::T_Val, XlsxAxis::Left, 1, 0))); + // The order the axes?? + const_cast(this)->axisList.append( + QSharedPointer(new XlsxAxis(XlsxAxis::T_Cat, XlsxAxis::Bottom, 0, 1))); + const_cast(this)->axisList.append( + QSharedPointer(new XlsxAxis(XlsxAxis::T_Val, XlsxAxis::Left, 1, 0))); } - //Note: Bar3D have 2~3 axes - Q_ASSERT(axisList.size()==2 || (axisList.size()==3 && chartType==Chart::CT_Bar3D)); + // Note: Bar3D have 2~3 axes + Q_ASSERT(axisList.size() == 2 || (axisList.size() == 3 && chartType == Chart::CT_Bar3D)); - for (int i=0; iaxisId)); } - writer.writeEndElement(); //barChart, bar3DChart + writer.writeEndElement(); // barChart, bar3DChart } void ChartPrivate::saveXmlLineChart(QXmlStreamWriter &writer) const { - QString name = chartType==Chart::CT_Line ? QStringLiteral("c:lineChart") : QStringLiteral("c:line3DChart"); + QString name = chartType == Chart::CT_Line ? QStringLiteral("c:lineChart") + : QStringLiteral("c:line3DChart"); writer.writeStartElement(name); writer.writeEmptyElement(QStringLiteral("grouping")); - for (int i=0; i(this)->axisList.append(QSharedPointer(new XlsxAxis(XlsxAxis::T_Cat, XlsxAxis::Bottom, 0, 1))); - const_cast(this)->axisList.append(QSharedPointer(new XlsxAxis(XlsxAxis::T_Val, XlsxAxis::Left, 1, 0))); - if (chartType==Chart::CT_Line3D) - const_cast(this)->axisList.append(QSharedPointer(new XlsxAxis(XlsxAxis::T_Ser, XlsxAxis::Bottom, 2, 0))); + const_cast(this)->axisList.append( + QSharedPointer(new XlsxAxis(XlsxAxis::T_Cat, XlsxAxis::Bottom, 0, 1))); + const_cast(this)->axisList.append( + QSharedPointer(new XlsxAxis(XlsxAxis::T_Val, XlsxAxis::Left, 1, 0))); + if (chartType == Chart::CT_Line3D) + const_cast(this)->axisList.append( + QSharedPointer(new XlsxAxis(XlsxAxis::T_Ser, XlsxAxis::Bottom, 2, 0))); } - Q_ASSERT((axisList.size()==2||chartType==Chart::CT_Line)|| (axisList.size()==3 && chartType==Chart::CT_Line3D)); + Q_ASSERT((axisList.size() == 2 || chartType == Chart::CT_Line) + || (axisList.size() == 3 && chartType == Chart::CT_Line3D)); - for (int i=0; iaxisId)); } - writer.writeEndElement(); //lineChart, line3DChart + writer.writeEndElement(); // lineChart, line3DChart } void ChartPrivate::saveXmlScatterChart(QXmlStreamWriter &writer) const @@ -460,49 +490,54 @@ void ChartPrivate::saveXmlScatterChart(QXmlStreamWriter &writer) const writer.writeEmptyElement(QStringLiteral("c:scatterStyle")); - for (int i=0; i(this)->axisList.append(QSharedPointer(new XlsxAxis(XlsxAxis::T_Val, XlsxAxis::Bottom, 0, 1))); - const_cast(this)->axisList.append(QSharedPointer(new XlsxAxis(XlsxAxis::T_Val, XlsxAxis::Left, 1, 0))); + const_cast(this)->axisList.append( + QSharedPointer(new XlsxAxis(XlsxAxis::T_Val, XlsxAxis::Bottom, 0, 1))); + const_cast(this)->axisList.append( + QSharedPointer(new XlsxAxis(XlsxAxis::T_Val, XlsxAxis::Left, 1, 0))); } - Q_ASSERT(axisList.size()==2); + Q_ASSERT(axisList.size() == 2); - for (int i=0; iaxisId)); } - writer.writeEndElement(); //c:scatterChart + writer.writeEndElement(); // c:scatterChart } void ChartPrivate::saveXmlAreaChart(QXmlStreamWriter &writer) const { - QString name = chartType==Chart::CT_Area ? QStringLiteral("c:areaChart") : QStringLiteral("c:area3DChart"); + QString name = chartType == Chart::CT_Area ? QStringLiteral("c:areaChart") + : QStringLiteral("c:area3DChart"); writer.writeStartElement(name); writer.writeEmptyElement(QStringLiteral("grouping")); - for (int i=0; i(this)->axisList.append(QSharedPointer(new XlsxAxis(XlsxAxis::T_Cat, XlsxAxis::Bottom, 0, 1))); - const_cast(this)->axisList.append(QSharedPointer(new XlsxAxis(XlsxAxis::T_Val, XlsxAxis::Left, 1, 0))); + const_cast(this)->axisList.append( + QSharedPointer(new XlsxAxis(XlsxAxis::T_Cat, XlsxAxis::Bottom, 0, 1))); + const_cast(this)->axisList.append( + QSharedPointer(new XlsxAxis(XlsxAxis::T_Val, XlsxAxis::Left, 1, 0))); } - //Note: Area3D have 2~3 axes - Q_ASSERT(axisList.size()==2 || (axisList.size()==3 && chartType==Chart::CT_Area3D)); + // Note: Area3D have 2~3 axes + Q_ASSERT(axisList.size() == 2 || (axisList.size() == 3 && chartType == Chart::CT_Area3D)); - for (int i=0; iaxisId)); } - writer.writeEndElement(); //lineChart, line3DChart + writer.writeEndElement(); // lineChart, line3DChart } void ChartPrivate::saveXmlDoughnutChart(QXmlStreamWriter &writer) const @@ -514,7 +549,7 @@ void ChartPrivate::saveXmlDoughnutChart(QXmlStreamWriter &writer) const writer.writeEmptyElement(QStringLiteral("c:varyColors")); writer.writeAttribute(QStringLiteral("val"), QStringLiteral("1")); - for (int i=0; iaxDataSource_numRef); - writer.writeEndElement();//c:numRef - writer.writeEndElement();//c:cat or c:xVal + writer.writeEndElement(); // c:numRef + writer.writeEndElement(); // c:cat or c:xVal } if (!ser->numberDataSource_numRef.isEmpty()) { @@ -549,11 +584,11 @@ void ChartPrivate::saveXmlSer(QXmlStreamWriter &writer, XlsxSeries *ser, int id) writer.writeStartElement(QStringLiteral("c:val")); writer.writeStartElement(QStringLiteral("c:numRef")); writer.writeTextElement(QStringLiteral("c:f"), ser->numberDataSource_numRef); - writer.writeEndElement();//c:numRef - writer.writeEndElement();//c:val or c:yVal + writer.writeEndElement(); // c:numRef + writer.writeEndElement(); // c:val or c:yVal } - writer.writeEndElement();//c:ser + writer.writeEndElement(); // c:ser } bool ChartPrivate::loadXmlAxis(QXmlStreamReader &reader) @@ -579,11 +614,11 @@ bool ChartPrivate::loadXmlAxis(QXmlStreamReader &reader) if (reader.name() == QLatin1String("axPos")) { QXmlStreamAttributes attrs = reader.attributes(); QStringRef pos = attrs.value(QLatin1String("val")); - if (pos==QLatin1String("l")) + if (pos == QLatin1String("l")) axis->axisPos = XlsxAxis::Left; - else if (pos==QLatin1String("r")) + else if (pos == QLatin1String("r")) axis->axisPos = XlsxAxis::Right; - else if (pos==QLatin1String("b")) + else if (pos == QLatin1String("b")) axis->axisPos = XlsxAxis::Bottom; else axis->axisPos = XlsxAxis::Top; @@ -592,8 +627,7 @@ bool ChartPrivate::loadXmlAxis(QXmlStreamReader &reader) } else if (reader.name() == QLatin1String("crossAx")) { axis->crossAx = reader.attributes().value(QLatin1String("val")).toString().toInt(); } - } else if (reader.tokenType() == QXmlStreamReader::EndElement - && reader.name() == name) { + } else if (reader.tokenType() == QXmlStreamReader::EndElement && reader.name() == name) { break; } } @@ -603,24 +637,42 @@ bool ChartPrivate::loadXmlAxis(QXmlStreamReader &reader) void ChartPrivate::saveXmlAxes(QXmlStreamWriter &writer) const { - for (int i=0; itype) { - case XlsxAxis::T_Cat: name = QStringLiteral("c:catAx"); break; - case XlsxAxis::T_Val: name = QStringLiteral("c:valAx"); break; - case XlsxAxis::T_Ser: name = QStringLiteral("c:serAx"); break; - case XlsxAxis::T_Date: name = QStringLiteral("c:dateAx"); break; - default: break; + case XlsxAxis::T_Cat: + name = QStringLiteral("c:catAx"); + break; + case XlsxAxis::T_Val: + name = QStringLiteral("c:valAx"); + break; + case XlsxAxis::T_Ser: + name = QStringLiteral("c:serAx"); + break; + case XlsxAxis::T_Date: + name = QStringLiteral("c:dateAx"); + break; + default: + break; } QString pos; switch (axis->axisPos) { - case XlsxAxis::Top: pos = QStringLiteral("t"); break; - case XlsxAxis::Bottom: pos = QStringLiteral("b"); break; - case XlsxAxis::Left: pos = QStringLiteral("l"); break; - case XlsxAxis::Right: pos = QStringLiteral("r"); break; - default: break; + case XlsxAxis::Top: + pos = QStringLiteral("t"); + break; + case XlsxAxis::Bottom: + pos = QStringLiteral("b"); + break; + case XlsxAxis::Left: + pos = QStringLiteral("l"); + break; + case XlsxAxis::Right: + pos = QStringLiteral("r"); + break; + default: + break; } writer.writeStartElement(name); @@ -630,7 +682,7 @@ void ChartPrivate::saveXmlAxes(QXmlStreamWriter &writer) const writer.writeStartElement(QStringLiteral("c:scaling")); writer.writeEmptyElement(QStringLiteral("c:orientation")); writer.writeAttribute(QStringLiteral("val"), QStringLiteral("minMax")); - writer.writeEndElement();//c:scaling + writer.writeEndElement(); // c:scaling writer.writeEmptyElement(QStringLiteral("c:axPos")); writer.writeAttribute(QStringLiteral("val"), pos); @@ -638,7 +690,7 @@ void ChartPrivate::saveXmlAxes(QXmlStreamWriter &writer) const writer.writeEmptyElement(QStringLiteral("c:crossAx")); writer.writeAttribute(QStringLiteral("val"), QString::number(axis->crossAx)); - writer.writeEndElement();//name + writer.writeEndElement(); // name } } diff --git a/src/xlsx/xlsxchart.h b/src/xlsx/xlsxchart.h index fcd8e2d..db50945 100644 --- a/src/xlsx/xlsxchart.h +++ b/src/xlsx/xlsxchart.h @@ -47,7 +47,7 @@ class Q_XLSX_EXPORT Chart : public AbstractOOXmlFile public: enum ChartType { - CT_Area = 1, //Zero is internally used for unknown types + CT_Area = 1, // Zero is internally used for unknown types CT_Area3D, CT_Line, CT_Line3D, @@ -67,7 +67,7 @@ public: ~Chart(); - void addSeries(const CellRange &range, AbstractSheet *sheet=0); + void addSeries(const CellRange &range, AbstractSheet *sheet = 0); void setChartType(ChartType type); void setChartStyle(int id); @@ -86,4 +86,3 @@ private: QT_END_NAMESPACE_XLSX #endif // QXLSX_CHART_H - diff --git a/src/xlsx/xlsxchart_p.h b/src/xlsx/xlsxchart_p.h index 4fcd0fb..48c0c7f 100644 --- a/src/xlsx/xlsxchart_p.h +++ b/src/xlsx/xlsxchart_p.h @@ -50,39 +50,30 @@ namespace QXlsx { class XlsxSeries { public: - //At present, we care about number cell ranges only! - QString numberDataSource_numRef; //yval, val - QString axDataSource_numRef; //xval, cat + // At present, we care about number cell ranges only! + QString numberDataSource_numRef; // yval, val + QString axDataSource_numRef; // xval, cat }; class XlsxAxis { public: - enum Type - { - T_Cat, - T_Val, - T_Date, - T_Ser - }; + enum Type { T_Cat, T_Val, T_Date, T_Ser }; - enum Pos - { - Left, - Right, - Top, - Bottom - }; + enum Pos { Left, Right, Top, Bottom }; - XlsxAxis(){} + XlsxAxis() {} XlsxAxis(Type t, Pos p, int id, int crossId) - :type(t), axisPos(p), axisId(id), crossAx(crossId) + : type(t) + , axisPos(p) + , axisId(id) + , crossAx(crossId) { } Type type; - Pos axisPos; //l,r,b,t + Pos axisPos; // l,r,b,t int axisId; int crossAx; }; @@ -114,8 +105,8 @@ public: Chart::ChartType chartType; - QList > seriesList; - QList > axisList; + QList> seriesList; + QList> axisList; AbstractSheet *sheet; }; diff --git a/src/xlsx/xlsxchartsheet.cpp b/src/xlsx/xlsxchartsheet.cpp index 5cf477c..d148776 100644 --- a/src/xlsx/xlsxchartsheet.cpp +++ b/src/xlsx/xlsxchartsheet.cpp @@ -37,9 +37,9 @@ QT_BEGIN_NAMESPACE_XLSX ChartsheetPrivate::ChartsheetPrivate(Chartsheet *p, Chartsheet::CreateFlag flag) - : AbstractSheetPrivate(p, flag), chart(0) + : AbstractSheetPrivate(p, flag) + , chart(0) { - } ChartsheetPrivate::~ChartsheetPrivate() @@ -56,14 +56,15 @@ ChartsheetPrivate::~ChartsheetPrivate() * \internal */ Chartsheet::Chartsheet(const QString &name, int id, Workbook *workbook, CreateFlag flag) - :AbstractSheet(name, id, workbook, new ChartsheetPrivate(this, flag)) + : AbstractSheet(name, id, workbook, new ChartsheetPrivate(this, flag)) { setSheetType(ST_ChartSheet); if (flag == Chartsheet::F_NewFromScratch) { d_func()->drawing = QSharedPointer(new Drawing(this, flag)); - DrawingAbsoluteAnchor *anchor = new DrawingAbsoluteAnchor(drawing(), DrawingAnchor::Picture); + DrawingAbsoluteAnchor *anchor = + new DrawingAbsoluteAnchor(drawing(), DrawingAnchor::Picture); anchor->pos = QPoint(0, 0); anchor->ext = QSize(9293679, 6068786); @@ -115,23 +116,28 @@ void Chartsheet::saveToXmlFile(QIODevice *device) const QXmlStreamWriter writer(device); writer.writeStartDocument(QStringLiteral("1.0"), true); - writer.writeDefaultNamespace(QStringLiteral("http://schemas.openxmlformats.org/spreadsheetml/2006/main")); - writer.writeNamespace(QStringLiteral("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), QStringLiteral("r")); + writer.writeDefaultNamespace( + QStringLiteral("http://schemas.openxmlformats.org/spreadsheetml/2006/main")); + writer.writeNamespace( + QStringLiteral("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), + QStringLiteral("r")); writer.writeStartElement(QStringLiteral("chartsheet")); writer.writeStartElement(QStringLiteral("sheetViews")); writer.writeEmptyElement(QStringLiteral("sheetView")); writer.writeAttribute(QStringLiteral("workbookViewId"), QString::number(0)); writer.writeAttribute(QStringLiteral("zoomToFit"), QStringLiteral("1")); - writer.writeEndElement(); //sheetViews + writer.writeEndElement(); // sheetViews int idx = d->workbook->drawings().indexOf(d->drawing.data()); - d->relationships->addWorksheetRelationship(QStringLiteral("/drawing"), QStringLiteral("../drawings/drawing%1.xml").arg(idx+1)); + d->relationships->addWorksheetRelationship( + QStringLiteral("/drawing"), QStringLiteral("../drawings/drawing%1.xml").arg(idx + 1)); writer.writeEmptyElement(QStringLiteral("drawing")); - writer.writeAttribute(QStringLiteral("r:id"), QStringLiteral("rId%1").arg(d->relationships->count())); + writer.writeAttribute(QStringLiteral("r:id"), + QStringLiteral("rId%1").arg(d->relationships->count())); - writer.writeEndElement();//chartsheet + writer.writeEndElement(); // chartsheet writer.writeEndDocument(); } @@ -146,7 +152,8 @@ bool Chartsheet::loadFromXmlFile(QIODevice *device) if (reader.name() == QLatin1String("drawing")) { QString rId = reader.attributes().value(QStringLiteral("r:id")).toString(); QString name = d->relationships->getRelationshipById(rId).target; - QString path = QDir::cleanPath(splitPath(filePath())[0] + QLatin1String("/") + name); + QString path = + QDir::cleanPath(splitPath(filePath())[0] + QLatin1String("/") + name); d->drawing = QSharedPointer(new Drawing(this, F_LoadFromExists)); d->drawing->setFilePath(path); } diff --git a/src/xlsx/xlsxchartsheet.h b/src/xlsx/xlsxchartsheet.h index 6c5ee98..ebc2713 100644 --- a/src/xlsx/xlsxchartsheet.h +++ b/src/xlsx/xlsxchartsheet.h @@ -38,7 +38,6 @@ class Q_XLSX_EXPORT Chartsheet : public AbstractSheet { Q_DECLARE_PRIVATE(Chartsheet) public: - ~Chartsheet(); Chart *chart(); diff --git a/src/xlsx/xlsxchartsheet_p.h b/src/xlsx/xlsxchartsheet_p.h index 817da88..009f5b5 100644 --- a/src/xlsx/xlsxchartsheet_p.h +++ b/src/xlsx/xlsxchartsheet_p.h @@ -51,6 +51,5 @@ public: Chart *chart; }; - } #endif // XLSXCHARTSHEET_P_H diff --git a/src/xlsx/xlsxcolor.cpp b/src/xlsx/xlsxcolor.cpp index b1ed463..0601ac8 100644 --- a/src/xlsx/xlsxcolor.cpp +++ b/src/xlsx/xlsxcolor.cpp @@ -9,7 +9,6 @@ namespace QXlsx { - XlsxColor::XlsxColor(const QColor &color) { if (color.isValid()) @@ -17,15 +16,13 @@ XlsxColor::XlsxColor(const QColor &color) } XlsxColor::XlsxColor(const QString &theme, const QString &tint) - :val(QStringList()<(), this); } - QColor XlsxColor::fromARGBString(const QString &c) { Q_ASSERT(c.length() == 8); @@ -140,15 +136,15 @@ QString XlsxColor::toARGBString(const QColor &c) QDataStream &operator<<(QDataStream &s, const XlsxColor &color) { if (color.isInvalid()) - s<<0; + s << 0; else if (color.isRgbColor()) - s<<1<>(QDataStream &s, XlsxColor &color) { int marker(4); - s>>marker; + s >> marker; if (marker == 0) { color = XlsxColor(); } else if (marker == 1) { QColor c; - s>>c; + s >> c; color = XlsxColor(c); } else if (marker == 2) { int indexed; - s>>indexed; + s >> indexed; color = XlsxColor(indexed); } else if (marker == 3) { QStringList list; - s>>list; + s >> list; color = XlsxColor(list[0], list[1]); } diff --git a/src/xlsx/xlsxcolor_p.h b/src/xlsx/xlsxcolor_p.h index eff1b0b..a26e5a5 100644 --- a/src/xlsx/xlsxcolor_p.h +++ b/src/xlsx/xlsxcolor_p.h @@ -52,8 +52,8 @@ class Q_XLSX_EXPORT XlsxColor { public: explicit XlsxColor(const QColor &color = QColor()); - explicit XlsxColor(const QString &theme, const QString &tint=QString()); - explicit XlsxColor (int index); + explicit XlsxColor(const QString &theme, const QString &tint = QString()); + explicit XlsxColor(int index); bool isThemeColor() const; bool isIndexedColor() const; @@ -69,7 +69,7 @@ public: static QColor fromARGBString(const QString &c); static QString toARGBString(const QColor &c); - bool saveToXml(QXmlStreamWriter &writer, const QString &node=QString()) const; + bool saveToXml(QXmlStreamWriter &writer, const QString &node = QString()) const; bool loadFromXml(QXmlStreamReader &reader); private: diff --git a/src/xlsx/xlsxconditionalformatting.cpp b/src/xlsx/xlsxconditionalformatting.cpp index 03561fe..007677c 100644 --- a/src/xlsx/xlsxconditionalformatting.cpp +++ b/src/xlsx/xlsxconditionalformatting.cpp @@ -37,32 +37,44 @@ QT_BEGIN_NAMESPACE_XLSX ConditionalFormattingPrivate::ConditionalFormattingPrivate() { - } -ConditionalFormattingPrivate::ConditionalFormattingPrivate(const ConditionalFormattingPrivate &other) - :QSharedData(other) +ConditionalFormattingPrivate::ConditionalFormattingPrivate( + const ConditionalFormattingPrivate &other) + : QSharedData(other) { - } ConditionalFormattingPrivate::~ConditionalFormattingPrivate() { - } -void ConditionalFormattingPrivate::writeCfVo(QXmlStreamWriter &writer, const XlsxCfVoData &cfvo) const +void ConditionalFormattingPrivate::writeCfVo(QXmlStreamWriter &writer, + const XlsxCfVoData &cfvo) const { writer.writeEmptyElement(QStringLiteral("cfvo")); QString type; - switch(cfvo.type) { - case ConditionalFormatting::VOT_Formula: type=QStringLiteral("formula"); break; - case ConditionalFormatting::VOT_Max: type=QStringLiteral("max"); break; - case ConditionalFormatting::VOT_Min: type=QStringLiteral("min"); break; - case ConditionalFormatting::VOT_Num: type=QStringLiteral("num"); break; - case ConditionalFormatting::VOT_Percent: type=QStringLiteral("percent"); break; - case ConditionalFormatting::VOT_Percentile: type=QStringLiteral("percentile"); break; - default: break; + switch (cfvo.type) { + case ConditionalFormatting::VOT_Formula: + type = QStringLiteral("formula"); + break; + case ConditionalFormatting::VOT_Max: + type = QStringLiteral("max"); + break; + case ConditionalFormatting::VOT_Min: + type = QStringLiteral("min"); + break; + case ConditionalFormatting::VOT_Num: + type = QStringLiteral("num"); + break; + case ConditionalFormatting::VOT_Percent: + type = QStringLiteral("percent"); + break; + case ConditionalFormatting::VOT_Percentile: + type = QStringLiteral("percentile"); + break; + default: + break; } writer.writeAttribute(QStringLiteral("type"), type); writer.writeAttribute(QStringLiteral("val"), cfvo.value); @@ -78,7 +90,6 @@ void ConditionalFormattingPrivate::writeCfVo(QXmlStreamWriter &writer, const Xls * The conditional formatting can be applied to a single cell or ranges of cells. */ - /*! \enum ConditionalFormatting::HighlightRuleType @@ -140,18 +151,16 @@ void ConditionalFormattingPrivate::writeCfVo(QXmlStreamWriter &writer, const Xls Construct a conditional formatting object */ ConditionalFormatting::ConditionalFormatting() - :d(new ConditionalFormattingPrivate()) + : d(new ConditionalFormattingPrivate()) { - } /*! Constructs a copy of \a other. */ ConditionalFormatting::ConditionalFormatting(const ConditionalFormatting &other) - :d(other.d) + : d(other.d) { - } /*! @@ -164,7 +173,6 @@ ConditionalFormatting &ConditionalFormatting::operator=(const ConditionalFormatt return *this; } - /*! * Destroy the object. */ @@ -177,7 +185,9 @@ ConditionalFormatting::~ConditionalFormatting() * \a format and \a stopIfTrue. * Return false if failed. */ -bool ConditionalFormatting::addHighlightCellsRule(HighlightRuleType type, const QString &formula1, const QString &formula2, const Format &format, bool stopIfTrue) +bool ConditionalFormatting::addHighlightCellsRule(HighlightRuleType type, const QString &formula1, + const QString &formula2, const Format &format, + bool stopIfTrue) { if (format.isEmpty()) return false; @@ -189,34 +199,55 @@ bool ConditionalFormatting::addHighlightCellsRule(HighlightRuleType type, const cfRule->attrs[XlsxCfRuleData::A_type] = QStringLiteral("cellIs"); QString op; switch (type) { - case Highlight_Between: op = QStringLiteral("between"); break; - case Highlight_Equal: op = QStringLiteral("equal"); break; - case Highlight_GreaterThan: op = QStringLiteral("greaterThan"); break; - case Highlight_GreaterThanOrEqual: op = QStringLiteral("greaterThanOrEqual"); break; - case Highlight_LessThan: op = QStringLiteral("lessThan"); break; - case Highlight_LessThanOrEqual: op = QStringLiteral("lessThanOrEqual"); break; - case Highlight_NotBetween: op = QStringLiteral("notBetween"); break; - case Highlight_NotEqual: op = QStringLiteral("notEqual"); break; - default: break; + case Highlight_Between: + op = QStringLiteral("between"); + break; + case Highlight_Equal: + op = QStringLiteral("equal"); + break; + case Highlight_GreaterThan: + op = QStringLiteral("greaterThan"); + break; + case Highlight_GreaterThanOrEqual: + op = QStringLiteral("greaterThanOrEqual"); + break; + case Highlight_LessThan: + op = QStringLiteral("lessThan"); + break; + case Highlight_LessThanOrEqual: + op = QStringLiteral("lessThanOrEqual"); + break; + case Highlight_NotBetween: + op = QStringLiteral("notBetween"); + break; + case Highlight_NotEqual: + op = QStringLiteral("notEqual"); + break; + default: + break; } cfRule->attrs[XlsxCfRuleData::A_operator] = op; } else if (type >= Highlight_ContainsText && type <= Highlight_EndsWith) { if (type == Highlight_ContainsText) { cfRule->attrs[XlsxCfRuleData::A_type] = QStringLiteral("containsText"); cfRule->attrs[XlsxCfRuleData::A_operator] = QStringLiteral("containsText"); - cfRule->attrs[XlsxCfRuleData::A_formula1_temp] = QStringLiteral("NOT(ISERROR(SEARCH(\"%1\",%2)))").arg(formula1); + cfRule->attrs[XlsxCfRuleData::A_formula1_temp] = + QStringLiteral("NOT(ISERROR(SEARCH(\"%1\",%2)))").arg(formula1); } else if (type == Highlight_NotContainsText) { cfRule->attrs[XlsxCfRuleData::A_type] = QStringLiteral("notContainsText"); cfRule->attrs[XlsxCfRuleData::A_operator] = QStringLiteral("notContains"); - cfRule->attrs[XlsxCfRuleData::A_formula1_temp] = QStringLiteral("ISERROR(SEARCH(\"%2\",%1))").arg(formula1); + cfRule->attrs[XlsxCfRuleData::A_formula1_temp] = + QStringLiteral("ISERROR(SEARCH(\"%2\",%1))").arg(formula1); } else if (type == Highlight_BeginsWith) { cfRule->attrs[XlsxCfRuleData::A_type] = QStringLiteral("beginsWith"); cfRule->attrs[XlsxCfRuleData::A_operator] = QStringLiteral("beginsWith"); - cfRule->attrs[XlsxCfRuleData::A_formula1_temp] = QStringLiteral("LEFT(%2,LEN(\"%1\"))=\"%1\"").arg(formula1); + cfRule->attrs[XlsxCfRuleData::A_formula1_temp] = + QStringLiteral("LEFT(%2,LEN(\"%1\"))=\"%1\"").arg(formula1); } else { cfRule->attrs[XlsxCfRuleData::A_type] = QStringLiteral("endsWith"); cfRule->attrs[XlsxCfRuleData::A_operator] = QStringLiteral("endsWith"); - cfRule->attrs[XlsxCfRuleData::A_formula1_temp] = QStringLiteral("RIGHT(%2,LEN(\"%1\"))=\"%1\"").arg(formula1); + cfRule->attrs[XlsxCfRuleData::A_formula1_temp] = + QStringLiteral("RIGHT(%2,LEN(\"%1\"))=\"%1\"").arg(formula1); } cfRule->attrs[XlsxCfRuleData::A_text] = formula1; skipFormula = true; @@ -250,7 +281,8 @@ bool ConditionalFormatting::addHighlightCellsRule(HighlightRuleType type, const cfRule->attrs[XlsxCfRuleData::A_bottom] = QStringLiteral("1"); if (type == Highlight_TopPercent || type == Highlight_BottomPercent) cfRule->attrs[XlsxCfRuleData::A_percent] = QStringLiteral("1"); - cfRule->attrs[XlsxCfRuleData::A_rank] = !formula1.isEmpty() ? formula1 : QStringLiteral("10"); + cfRule->attrs[XlsxCfRuleData::A_rank] = + !formula1.isEmpty() ? formula1 : QStringLiteral("10"); skipFormula = true; } else if (type >= Highlight_AboveAverage && type <= Highlight_BelowStdDev3) { cfRule->attrs[XlsxCfRuleData::A_type] = QStringLiteral("aboveAverage"); @@ -264,7 +296,7 @@ bool ConditionalFormatting::addHighlightCellsRule(HighlightRuleType type, const cfRule->attrs[XlsxCfRuleData::A_stdDev] = QStringLiteral("2"); else if (type == Highlight_AboveStdDev3 || type == Highlight_BelowStdDev3) cfRule->attrs[XlsxCfRuleData::A_stdDev] = QStringLiteral("3"); - } else if (type == Highlight_Expression){ + } else if (type == Highlight_Expression) { cfRule->attrs[XlsxCfRuleData::A_type] = QStringLiteral("expression"); } else { return false; @@ -275,9 +307,11 @@ bool ConditionalFormatting::addHighlightCellsRule(HighlightRuleType type, const cfRule->attrs[XlsxCfRuleData::A_stopIfTrue] = true; if (!skipFormula) { if (!formula1.isEmpty()) - cfRule->attrs[XlsxCfRuleData::A_formula1] = formula1.startsWith(QLatin1String("=")) ? formula1.mid(1) : formula1; + cfRule->attrs[XlsxCfRuleData::A_formula1] = + formula1.startsWith(QLatin1String("=")) ? formula1.mid(1) : formula1; if (!formula2.isEmpty()) - cfRule->attrs[XlsxCfRuleData::A_formula2] = formula2.startsWith(QLatin1String("=")) ? formula2.mid(1) : formula2; + cfRule->attrs[XlsxCfRuleData::A_formula2] = + formula2.startsWith(QLatin1String("=")) ? formula2.mid(1) : formula2; } d->cfRules.append(cfRule); return true; @@ -288,10 +322,11 @@ bool ConditionalFormatting::addHighlightCellsRule(HighlightRuleType type, const * * Add a hightlight rule with the given \a type \a format and \a stopIfTrue. */ -bool ConditionalFormatting::addHighlightCellsRule(HighlightRuleType type, const Format &format, bool stopIfTrue) +bool ConditionalFormatting::addHighlightCellsRule(HighlightRuleType type, const Format &format, + bool stopIfTrue) { if ((type >= Highlight_AboveAverage && type <= Highlight_BelowStdDev3) - || (type >= Highlight_Duplicate && type <= Highlight_NoErrors)) { + || (type >= Highlight_Duplicate && type <= Highlight_NoErrors)) { return addHighlightCellsRule(type, QString(), QString(), format, stopIfTrue); } @@ -304,7 +339,8 @@ bool ConditionalFormatting::addHighlightCellsRule(HighlightRuleType type, const * Add a hightlight rule with the given \a type, \a formula, \a format and \a stopIfTrue. * Return false if failed. */ -bool ConditionalFormatting::addHighlightCellsRule(HighlightRuleType type, const QString &formula, const Format &format, bool stopIfTrue) +bool ConditionalFormatting::addHighlightCellsRule(HighlightRuleType type, const QString &formula, + const Format &format, bool stopIfTrue) { if (type == Highlight_Between || type == Highlight_NotBetween) return false; @@ -317,7 +353,9 @@ bool ConditionalFormatting::addHighlightCellsRule(HighlightRuleType type, const * , \a type2, \a val2, \a showData and \a stopIfTrue. * Return false if failed. */ -bool ConditionalFormatting::addDataBarRule(const QColor &color, ValueObjectType type1, const QString &val1, ValueObjectType type2, const QString &val2, bool showData, bool stopIfTrue) +bool ConditionalFormatting::addDataBarRule(const QColor &color, ValueObjectType type1, + const QString &val1, ValueObjectType type2, + const QString &val2, bool showData, bool stopIfTrue) { QSharedPointer cfRule(new XlsxCfRuleData); @@ -343,14 +381,16 @@ bool ConditionalFormatting::addDataBarRule(const QColor &color, ValueObjectType */ bool ConditionalFormatting::addDataBarRule(const QColor &color, bool showData, bool stopIfTrue) { - return addDataBarRule(color, VOT_Min, QStringLiteral("0"), VOT_Max, QStringLiteral("0"), showData, stopIfTrue); + return addDataBarRule(color, VOT_Min, QStringLiteral("0"), VOT_Max, QStringLiteral("0"), + showData, stopIfTrue); } /*! * Add a colorScale rule with the given \a minColor, \a maxColor and \a stopIfTrue. * Return false if failed. */ -bool ConditionalFormatting::add2ColorScaleRule(const QColor &minColor, const QColor &maxColor, bool stopIfTrue) +bool ConditionalFormatting::add2ColorScaleRule(const QColor &minColor, const QColor &maxColor, + bool stopIfTrue) { ValueObjectType type1 = VOT_Min; ValueObjectType type2 = VOT_Max; @@ -378,7 +418,8 @@ bool ConditionalFormatting::add2ColorScaleRule(const QColor &minColor, const QCo * Add a colorScale rule with the given \a minColor, \a midColor, \a maxColor and \a stopIfTrue. * Return false if failed. */ -bool ConditionalFormatting::add3ColorScaleRule(const QColor &minColor, const QColor &midColor, const QColor &maxColor, bool stopIfTrue) +bool ConditionalFormatting::add3ColorScaleRule(const QColor &minColor, const QColor &midColor, + const QColor &maxColor, bool stopIfTrue) { ValueObjectType type1 = VOT_Min; ValueObjectType type2 = VOT_Percent; @@ -451,7 +492,8 @@ void ConditionalFormatting::addRange(const CellRange &range) d->ranges.append(range); } -bool ConditionalFormattingPrivate::readCfRule(QXmlStreamReader &reader, XlsxCfRuleData *rule, Styles *styles) +bool ConditionalFormattingPrivate::readCfRule(QXmlStreamReader &reader, XlsxCfRuleData *rule, + Styles *styles) { Q_ASSERT(reader.name() == QLatin1String("cfRule")); QXmlStreamAttributes attrs = reader.attributes(); @@ -466,19 +508,19 @@ bool ConditionalFormattingPrivate::readCfRule(QXmlStreamReader &reader, XlsxCfRu } rule->priority = attrs.value(QLatin1String("priority")).toString().toInt(); if (attrs.value(QLatin1String("stopIfTrue")) == QLatin1String("1")) { - //default is false + // default is false rule->attrs[XlsxCfRuleData::A_stopIfTrue] = QLatin1String("1"); } if (attrs.value(QLatin1String("aboveAverage")) == QLatin1String("0")) { - //default is true + // default is true rule->attrs[XlsxCfRuleData::A_aboveAverage] = QLatin1String("0"); } if (attrs.value(QLatin1String("percent")) == QLatin1String("1")) { - //default is false + // default is false rule->attrs[XlsxCfRuleData::A_percent] = QLatin1String("1"); } if (attrs.value(QLatin1String("bottom")) == QLatin1String("1")) { - //default is false + // default is false rule->attrs[XlsxCfRuleData::A_bottom] = QLatin1String("1"); } if (attrs.hasAttribute(QLatin1String("operator"))) @@ -488,7 +530,8 @@ bool ConditionalFormattingPrivate::readCfRule(QXmlStreamReader &reader, XlsxCfRu rule->attrs[XlsxCfRuleData::A_text] = attrs.value(QLatin1String("text")).toString(); if (attrs.hasAttribute(QLatin1String("timePeriod"))) - rule->attrs[XlsxCfRuleData::A_timePeriod] = attrs.value(QLatin1String("timePeriod")).toString(); + rule->attrs[XlsxCfRuleData::A_timePeriod] = + attrs.value(QLatin1String("timePeriod")).toString(); if (attrs.hasAttribute(QLatin1String("rank"))) rule->attrs[XlsxCfRuleData::A_rank] = attrs.value(QLatin1String("rank")).toString(); @@ -497,7 +540,7 @@ bool ConditionalFormattingPrivate::readCfRule(QXmlStreamReader &reader, XlsxCfRu rule->attrs[XlsxCfRuleData::A_stdDev] = attrs.value(QLatin1String("stdDev")).toString(); if (attrs.value(QLatin1String("equalAverage")) == QLatin1String("1")) { - //default is false + // default is false rule->attrs[XlsxCfRuleData::A_equalAverage] = QLatin1String("1"); } @@ -519,7 +562,7 @@ bool ConditionalFormattingPrivate::readCfRule(QXmlStreamReader &reader, XlsxCfRu } } if (reader.tokenType() == QXmlStreamReader::EndElement - && reader.name() == QStringLiteral("conditionalFormatting")) { + && reader.name() == QStringLiteral("conditionalFormatting")) { break; } } @@ -550,7 +593,7 @@ bool ConditionalFormattingPrivate::readCfDataBar(QXmlStreamReader &reader, XlsxC } } if (reader.tokenType() == QXmlStreamReader::EndElement - && reader.name() == QStringLiteral("dataBar")) { + && reader.name() == QStringLiteral("dataBar")) { break; } } @@ -586,7 +629,7 @@ bool ConditionalFormattingPrivate::readCfColorScale(QXmlStreamReader &reader, Xl } } if (reader.tokenType() == QXmlStreamReader::EndElement - && reader.name() == QStringLiteral("colorScale")) { + && reader.name() == QStringLiteral("colorScale")) { break; } } @@ -612,13 +655,13 @@ bool ConditionalFormattingPrivate::readCfVo(QXmlStreamReader &reader, XlsxCfVoDa t = ConditionalFormatting::VOT_Num; else if (type == QLatin1String("percent")) t = ConditionalFormatting::VOT_Percent; - else //if (type == QLatin1String("percentile")) + else // if (type == QLatin1String("percentile")) t = ConditionalFormatting::VOT_Percentile; cfvo.type = t; cfvo.value = attrs.value(QLatin1String("val")).toString(); if (attrs.value(QLatin1String("gte")) == QLatin1String("0")) { - //default is true + // default is true cfvo.gte = false; } return true; @@ -645,12 +688,11 @@ bool ConditionalFormatting::loadFromXml(QXmlStreamReader &reader, Styles *styles } } if (reader.tokenType() == QXmlStreamReader::EndElement - && reader.name() == QStringLiteral("conditionalFormatting")) { + && reader.name() == QStringLiteral("conditionalFormatting")) { break; } } - return true; } @@ -662,33 +704,45 @@ bool ConditionalFormatting::saveToXml(QXmlStreamWriter &writer) const sqref.append(range.toString()); writer.writeAttribute(QStringLiteral("sqref"), sqref.join(QLatin1Char(' '))); - for (int i=0; icfRules.size(); ++i) { + for (int i = 0; i < d->cfRules.size(); ++i) { const QSharedPointer &rule = d->cfRules[i]; writer.writeStartElement(QStringLiteral("cfRule")); - writer.writeAttribute(QStringLiteral("type"), rule->attrs[XlsxCfRuleData::A_type].toString()); + writer.writeAttribute(QStringLiteral("type"), + rule->attrs[XlsxCfRuleData::A_type].toString()); if (rule->dxfFormat.dxfIndexValid()) - writer.writeAttribute(QStringLiteral("dxfId"), QString::number(rule->dxfFormat.dxfIndex())); + writer.writeAttribute(QStringLiteral("dxfId"), + QString::number(rule->dxfFormat.dxfIndex())); writer.writeAttribute(QStringLiteral("priority"), QString::number(rule->priority)); if (rule->attrs.contains(XlsxCfRuleData::A_stopIfTrue)) - writer.writeAttribute(QStringLiteral("stopIfTrue"), rule->attrs[XlsxCfRuleData::A_stopIfTrue].toString()); + writer.writeAttribute(QStringLiteral("stopIfTrue"), + rule->attrs[XlsxCfRuleData::A_stopIfTrue].toString()); if (rule->attrs.contains(XlsxCfRuleData::A_aboveAverage)) - writer.writeAttribute(QStringLiteral("aboveAverage"), rule->attrs[XlsxCfRuleData::A_aboveAverage].toString()); + writer.writeAttribute(QStringLiteral("aboveAverage"), + rule->attrs[XlsxCfRuleData::A_aboveAverage].toString()); if (rule->attrs.contains(XlsxCfRuleData::A_percent)) - writer.writeAttribute(QStringLiteral("percent"), rule->attrs[XlsxCfRuleData::A_percent].toString()); + writer.writeAttribute(QStringLiteral("percent"), + rule->attrs[XlsxCfRuleData::A_percent].toString()); if (rule->attrs.contains(XlsxCfRuleData::A_bottom)) - writer.writeAttribute(QStringLiteral("bottom"), rule->attrs[XlsxCfRuleData::A_bottom].toString()); + writer.writeAttribute(QStringLiteral("bottom"), + rule->attrs[XlsxCfRuleData::A_bottom].toString()); if (rule->attrs.contains(XlsxCfRuleData::A_operator)) - writer.writeAttribute(QStringLiteral("operator"), rule->attrs[XlsxCfRuleData::A_operator].toString()); + writer.writeAttribute(QStringLiteral("operator"), + rule->attrs[XlsxCfRuleData::A_operator].toString()); if (rule->attrs.contains(XlsxCfRuleData::A_text)) - writer.writeAttribute(QStringLiteral("text"), rule->attrs[XlsxCfRuleData::A_text].toString()); + writer.writeAttribute(QStringLiteral("text"), + rule->attrs[XlsxCfRuleData::A_text].toString()); if (rule->attrs.contains(XlsxCfRuleData::A_timePeriod)) - writer.writeAttribute(QStringLiteral("timePeriod"), rule->attrs[XlsxCfRuleData::A_timePeriod].toString()); + writer.writeAttribute(QStringLiteral("timePeriod"), + rule->attrs[XlsxCfRuleData::A_timePeriod].toString()); if (rule->attrs.contains(XlsxCfRuleData::A_rank)) - writer.writeAttribute(QStringLiteral("rank"), rule->attrs[XlsxCfRuleData::A_rank].toString()); + writer.writeAttribute(QStringLiteral("rank"), + rule->attrs[XlsxCfRuleData::A_rank].toString()); if (rule->attrs.contains(XlsxCfRuleData::A_stdDev)) - writer.writeAttribute(QStringLiteral("stdDev"), rule->attrs[XlsxCfRuleData::A_stdDev].toString()); + writer.writeAttribute(QStringLiteral("stdDev"), + rule->attrs[XlsxCfRuleData::A_stdDev].toString()); if (rule->attrs.contains(XlsxCfRuleData::A_equalAverage)) - writer.writeAttribute(QStringLiteral("equalAverage"), rule->attrs[XlsxCfRuleData::A_equalAverage].toString()); + writer.writeAttribute(QStringLiteral("equalAverage"), + rule->attrs[XlsxCfRuleData::A_equalAverage].toString()); if (rule->attrs[XlsxCfRuleData::A_type] == QLatin1String("dataBar")) { writer.writeStartElement(QStringLiteral("dataBar")); @@ -697,7 +751,7 @@ bool ConditionalFormatting::saveToXml(QXmlStreamWriter &writer) const d->writeCfVo(writer, rule->attrs[XlsxCfRuleData::A_cfvo1].value()); d->writeCfVo(writer, rule->attrs[XlsxCfRuleData::A_cfvo2].value()); rule->attrs[XlsxCfRuleData::A_color1].value().saveToXml(writer); - writer.writeEndElement();//dataBar + writer.writeEndElement(); // dataBar } else if (rule->attrs[XlsxCfRuleData::A_type] == QLatin1String("colorScale")) { writer.writeStartElement(QStringLiteral("colorScale")); d->writeCfVo(writer, rule->attrs[XlsxCfRuleData::A_cfvo1].value()); @@ -710,25 +764,29 @@ bool ConditionalFormatting::saveToXml(QXmlStreamWriter &writer) const if (rule->attrs.contains(XlsxCfRuleData::A_color3)) rule->attrs[XlsxCfRuleData::A_color3].value().saveToXml(writer); - writer.writeEndElement();//colorScale + writer.writeEndElement(); // colorScale } - if (rule->attrs.contains(XlsxCfRuleData::A_formula1_temp)) { QString startCell = ranges()[0].toString().split(QLatin1Char(':'))[0]; - writer.writeTextElement(QStringLiteral("formula"), rule->attrs[XlsxCfRuleData::A_formula1_temp].toString().arg(startCell)); + writer.writeTextElement( + QStringLiteral("formula"), + rule->attrs[XlsxCfRuleData::A_formula1_temp].toString().arg(startCell)); } else if (rule->attrs.contains(XlsxCfRuleData::A_formula1)) { - writer.writeTextElement(QStringLiteral("formula"), rule->attrs[XlsxCfRuleData::A_formula1].toString()); + writer.writeTextElement(QStringLiteral("formula"), + rule->attrs[XlsxCfRuleData::A_formula1].toString()); } if (rule->attrs.contains(XlsxCfRuleData::A_formula2)) - writer.writeTextElement(QStringLiteral("formula"), rule->attrs[XlsxCfRuleData::A_formula2].toString()); + writer.writeTextElement(QStringLiteral("formula"), + rule->attrs[XlsxCfRuleData::A_formula2].toString()); if (rule->attrs.contains(XlsxCfRuleData::A_formula3)) - writer.writeTextElement(QStringLiteral("formula"), rule->attrs[XlsxCfRuleData::A_formula3].toString()); + writer.writeTextElement(QStringLiteral("formula"), + rule->attrs[XlsxCfRuleData::A_formula3].toString()); - writer.writeEndElement(); //cfRule + writer.writeEndElement(); // cfRule } - writer.writeEndElement(); //conditionalFormatting + writer.writeEndElement(); // conditionalFormatting return true; } diff --git a/src/xlsx/xlsxconditionalformatting.h b/src/xlsx/xlsxconditionalformatting.h index 45378f7..f77dc16 100644 --- a/src/xlsx/xlsxconditionalformatting.h +++ b/src/xlsx/xlsxconditionalformatting.h @@ -90,27 +90,27 @@ public: Highlight_Expression }; - enum ValueObjectType - { - VOT_Formula, - VOT_Max, - VOT_Min, - VOT_Num, - VOT_Percent, - VOT_Percentile - }; + enum ValueObjectType { VOT_Formula, VOT_Max, VOT_Min, VOT_Num, VOT_Percent, VOT_Percentile }; ConditionalFormatting(); ConditionalFormatting(const ConditionalFormatting &other); ~ConditionalFormatting(); - bool addHighlightCellsRule(HighlightRuleType type, const Format &format, bool stopIfTrue=false); - bool addHighlightCellsRule(HighlightRuleType type, const QString &formula1, const Format &format, bool stopIfTrue=false); - bool addHighlightCellsRule(HighlightRuleType type, const QString &formula1, const QString &formula2, const Format &format, bool stopIfTrue=false); - bool addDataBarRule(const QColor &color, bool showData=true, bool stopIfTrue=false); - bool addDataBarRule(const QColor &color, ValueObjectType type1, const QString &val1, ValueObjectType type2, const QString &val2, bool showData=true, bool stopIfTrue=false); - bool add2ColorScaleRule(const QColor &minColor, const QColor &maxColor, bool stopIfTrue=false); - bool add3ColorScaleRule(const QColor &minColor, const QColor &midColor, const QColor &maxColor, bool stopIfTrue=false); + bool addHighlightCellsRule(HighlightRuleType type, const Format &format, + bool stopIfTrue = false); + bool addHighlightCellsRule(HighlightRuleType type, const QString &formula1, + const Format &format, bool stopIfTrue = false); + bool addHighlightCellsRule(HighlightRuleType type, const QString &formula1, + const QString &formula2, const Format &format, + bool stopIfTrue = false); + bool addDataBarRule(const QColor &color, bool showData = true, bool stopIfTrue = false); + bool addDataBarRule(const QColor &color, ValueObjectType type1, const QString &val1, + ValueObjectType type2, const QString &val2, bool showData = true, + bool stopIfTrue = false); + bool add2ColorScaleRule(const QColor &minColor, const QColor &maxColor, + bool stopIfTrue = false); + bool add3ColorScaleRule(const QColor &minColor, const QColor &midColor, const QColor &maxColor, + bool stopIfTrue = false); QList ranges() const; @@ -119,14 +119,14 @@ public: void addRange(int firstRow, int firstCol, int lastRow, int lastCol); void addRange(const CellRange &range); - //needed by QSharedDataPointer!! + // needed by QSharedDataPointer!! ConditionalFormatting &operator=(const ConditionalFormatting &other); private: friend class Worksheet; friend class ::ConditionalFormattingTest; bool saveToXml(QXmlStreamWriter &writer) const; - bool loadFromXml(QXmlStreamReader &reader, Styles *styles=0); + bool loadFromXml(QXmlStreamReader &reader, Styles *styles = 0); QSharedDataPointer d; }; diff --git a/src/xlsx/xlsxconditionalformatting_p.h b/src/xlsx/xlsxconditionalformatting_p.h index ff71e5b..9fe5280 100644 --- a/src/xlsx/xlsxconditionalformatting_p.h +++ b/src/xlsx/xlsxconditionalformatting_p.h @@ -50,12 +50,14 @@ class XlsxCfVoData { public: XlsxCfVoData() - :gte(true) + : gte(true) { } - XlsxCfVoData(ConditionalFormatting::ValueObjectType type, const QString &value, bool gte=true) - :type(type), value(value), gte(gte) + XlsxCfVoData(ConditionalFormatting::ValueObjectType type, const QString &value, bool gte = true) + : type(type) + , value(value) + , gte(gte) { } @@ -70,7 +72,7 @@ public: enum Attribute { A_type, A_dxfId, - //A_priority, + // A_priority, A_stopIfTrue, A_aboveAverage, A_percent, @@ -100,8 +102,9 @@ public: }; XlsxCfRuleData() - :priority(1) - {} + : priority(1) + { + } int priority; Format dxfFormat; @@ -115,13 +118,13 @@ public: ConditionalFormattingPrivate(const ConditionalFormattingPrivate &other); ~ConditionalFormattingPrivate(); - void writeCfVo(QXmlStreamWriter &writer, const XlsxCfVoData& cfvo) const; - bool readCfVo(QXmlStreamReader &reader, XlsxCfVoData& cfvo); + void writeCfVo(QXmlStreamWriter &writer, const XlsxCfVoData &cfvo) const; + bool readCfVo(QXmlStreamReader &reader, XlsxCfVoData &cfvo); bool readCfRule(QXmlStreamReader &reader, XlsxCfRuleData *cfRule, Styles *styles); bool readCfDataBar(QXmlStreamReader &reader, XlsxCfRuleData *cfRule); bool readCfColorScale(QXmlStreamReader &reader, XlsxCfRuleData *cfRule); - QList >cfRules; + QList> cfRules; QList ranges; }; diff --git a/src/xlsx/xlsxcontenttypes.cpp b/src/xlsx/xlsxcontenttypes.cpp index 8a500ac..0a53113 100755 --- a/src/xlsx/xlsxcontenttypes.cpp +++ b/src/xlsx/xlsxcontenttypes.cpp @@ -33,12 +33,13 @@ namespace QXlsx { ContentTypes::ContentTypes(CreateFlag flag) - :AbstractOOXmlFile(flag) + : AbstractOOXmlFile(flag) { m_package_prefix = QStringLiteral("application/vnd.openxmlformats-package."); m_document_prefix = QStringLiteral("application/vnd.openxmlformats-officedocument."); - m_defaults.insert(QStringLiteral("rels"), m_package_prefix + QStringLiteral("relationships+xml")); + m_defaults.insert(QStringLiteral("rels"), + m_package_prefix + QStringLiteral("relationships+xml")); m_defaults.insert(QStringLiteral("xml"), QStringLiteral("application/xml")); } @@ -54,67 +55,80 @@ void ContentTypes::addOverride(const QString &key, const QString &value) void ContentTypes::addDocPropApp() { - addOverride(QStringLiteral("/docProps/app.xml"), m_document_prefix + QStringLiteral("extended-properties+xml")); + addOverride(QStringLiteral("/docProps/app.xml"), + m_document_prefix + QStringLiteral("extended-properties+xml")); } void ContentTypes::addDocPropCore() { - addOverride(QStringLiteral("/docProps/core.xml"), m_package_prefix + QStringLiteral("core-properties+xml")); + addOverride(QStringLiteral("/docProps/core.xml"), + m_package_prefix + QStringLiteral("core-properties+xml")); } void ContentTypes::addStyles() { - addOverride(QStringLiteral("/xl/styles.xml"), m_document_prefix + QStringLiteral("spreadsheetml.styles+xml")); + addOverride(QStringLiteral("/xl/styles.xml"), + m_document_prefix + QStringLiteral("spreadsheetml.styles+xml")); } void ContentTypes::addTheme() { - addOverride(QStringLiteral("/xl/theme/theme1.xml"), m_document_prefix + QStringLiteral("theme+xml")); + addOverride(QStringLiteral("/xl/theme/theme1.xml"), + m_document_prefix + QStringLiteral("theme+xml")); } void ContentTypes::addWorkbook() { - addOverride(QStringLiteral("/xl/workbook.xml"), m_document_prefix + QStringLiteral("spreadsheetml.sheet.main+xml")); + addOverride(QStringLiteral("/xl/workbook.xml"), + m_document_prefix + QStringLiteral("spreadsheetml.sheet.main+xml")); } void ContentTypes::addWorksheetName(const QString &name) { - addOverride(QStringLiteral("/xl/worksheets/%1.xml").arg(name), m_document_prefix + QStringLiteral("spreadsheetml.worksheet+xml")); + addOverride(QStringLiteral("/xl/worksheets/%1.xml").arg(name), + m_document_prefix + QStringLiteral("spreadsheetml.worksheet+xml")); } void ContentTypes::addChartsheetName(const QString &name) { - addOverride(QStringLiteral("/xl/chartsheets/%1.xml").arg(name), m_document_prefix + QStringLiteral("spreadsheetml.chartsheet+xml")); + addOverride(QStringLiteral("/xl/chartsheets/%1.xml").arg(name), + m_document_prefix + QStringLiteral("spreadsheetml.chartsheet+xml")); } void ContentTypes::addDrawingName(const QString &name) { - addOverride(QStringLiteral("/xl/drawings/%1.xml").arg(name), m_document_prefix + QStringLiteral("drawing+xml")); + addOverride(QStringLiteral("/xl/drawings/%1.xml").arg(name), + m_document_prefix + QStringLiteral("drawing+xml")); } void ContentTypes::addChartName(const QString &name) { - addOverride(QStringLiteral("/xl/charts/%1.xml").arg(name), m_document_prefix + QStringLiteral("drawingml.chart+xml")); + addOverride(QStringLiteral("/xl/charts/%1.xml").arg(name), + m_document_prefix + QStringLiteral("drawingml.chart+xml")); } void ContentTypes::addCommentName(const QString &name) { - addOverride(QStringLiteral("/xl/%1.xml").arg(name), m_document_prefix + QStringLiteral("spreadsheetml.comments+xml")); + addOverride(QStringLiteral("/xl/%1.xml").arg(name), + m_document_prefix + QStringLiteral("spreadsheetml.comments+xml")); } void ContentTypes::addTableName(const QString &name) { - addOverride(QStringLiteral("/xl/tables/%1.xml").arg(name), m_document_prefix + QStringLiteral("spreadsheetml.table+xml")); + addOverride(QStringLiteral("/xl/tables/%1.xml").arg(name), + m_document_prefix + QStringLiteral("spreadsheetml.table+xml")); } void ContentTypes::addExternalLinkName(const QString &name) { - addOverride(QStringLiteral("/xl/externalLinks/%1.xml").arg(name), m_document_prefix + QStringLiteral("spreadsheetml.externalLink+xml")); + addOverride(QStringLiteral("/xl/externalLinks/%1.xml").arg(name), + m_document_prefix + QStringLiteral("spreadsheetml.externalLink+xml")); } void ContentTypes::addSharedString() { - addOverride(QStringLiteral("/xl/sharedStrings.xml"), m_document_prefix + QStringLiteral("spreadsheetml.sharedStrings+xml")); + addOverride(QStringLiteral("/xl/sharedStrings.xml"), + m_document_prefix + QStringLiteral("spreadsheetml.sharedStrings+xml")); } void ContentTypes::addVmlName() @@ -124,7 +138,8 @@ void ContentTypes::addVmlName() void ContentTypes::addCalcChain() { - addOverride(QStringLiteral("/xl/calcChain.xml"), m_document_prefix + QStringLiteral("spreadsheetml.calcChain+xml")); + addOverride(QStringLiteral("/xl/calcChain.xml"), + m_document_prefix + QStringLiteral("spreadsheetml.calcChain+xml")); } void ContentTypes::addVbaProject() @@ -144,33 +159,34 @@ void ContentTypes::saveToXmlFile(QIODevice *device) const writer.writeStartDocument(QStringLiteral("1.0"), true); writer.writeStartElement(QStringLiteral("Types")); - writer.writeAttribute(QStringLiteral("xmlns"), QStringLiteral("http://schemas.openxmlformats.org/package/2006/content-types")); + writer.writeAttribute( + QStringLiteral("xmlns"), + QStringLiteral("http://schemas.openxmlformats.org/package/2006/content-types")); { - QMapIterator it(m_defaults); - while (it.hasNext()) { - it.next(); - writer.writeStartElement(QStringLiteral("Default")); - writer.writeAttribute(QStringLiteral("Extension"), it.key()); - writer.writeAttribute(QStringLiteral("ContentType"), it.value()); - writer.writeEndElement();//Default - } + QMapIterator it(m_defaults); + while (it.hasNext()) { + it.next(); + writer.writeStartElement(QStringLiteral("Default")); + writer.writeAttribute(QStringLiteral("Extension"), it.key()); + writer.writeAttribute(QStringLiteral("ContentType"), it.value()); + writer.writeEndElement(); // Default + } } { - QMapIterator it(m_overrides); - while (it.hasNext()) { - it.next(); - writer.writeStartElement(QStringLiteral("Override")); - writer.writeAttribute(QStringLiteral("PartName"), it.key()); - writer.writeAttribute(QStringLiteral("ContentType"), it.value()); - writer.writeEndElement(); //Override - } + QMapIterator it(m_overrides); + while (it.hasNext()) { + it.next(); + writer.writeStartElement(QStringLiteral("Override")); + writer.writeAttribute(QStringLiteral("PartName"), it.key()); + writer.writeAttribute(QStringLiteral("ContentType"), it.value()); + writer.writeEndElement(); // Override + } } - writer.writeEndElement();//Types + writer.writeEndElement(); // Types writer.writeEndDocument(); - } bool ContentTypes::loadFromXmlFile(QIODevice *device) @@ -196,10 +212,10 @@ bool ContentTypes::loadFromXmlFile(QIODevice *device) } if (reader.hasError()) { - qDebug()< m_defaults; QMap m_overrides; @@ -83,6 +84,5 @@ private: QString m_package_prefix; QString m_document_prefix; }; - } #endif // XLSXCONTENTTYPES_H diff --git a/src/xlsx/xlsxdatavalidation.cpp b/src/xlsx/xlsxdatavalidation.cpp index c538c72..1542673 100644 --- a/src/xlsx/xlsxdatavalidation.cpp +++ b/src/xlsx/xlsxdatavalidation.cpp @@ -34,33 +34,43 @@ QT_BEGIN_NAMESPACE_XLSX DataValidationPrivate::DataValidationPrivate() - :validationType(DataValidation::None), validationOperator(DataValidation::Between) - , errorStyle(DataValidation::Stop), allowBlank(false), isPromptMessageVisible(true) + : validationType(DataValidation::None) + , validationOperator(DataValidation::Between) + , errorStyle(DataValidation::Stop) + , allowBlank(false) + , isPromptMessageVisible(true) , isErrorMessageVisible(true) { - } -DataValidationPrivate::DataValidationPrivate(DataValidation::ValidationType type, DataValidation::ValidationOperator op, const QString &formula1, const QString &formula2, bool allowBlank) - :validationType(type), validationOperator(op) - , errorStyle(DataValidation::Stop), allowBlank(allowBlank), isPromptMessageVisible(true) - , isErrorMessageVisible(true), formula1(formula1), formula2(formula2) +DataValidationPrivate::DataValidationPrivate(DataValidation::ValidationType type, + DataValidation::ValidationOperator op, + const QString &formula1, const QString &formula2, + bool allowBlank) + : validationType(type) + , validationOperator(op) + , errorStyle(DataValidation::Stop) + , allowBlank(allowBlank) + , isPromptMessageVisible(true) + , isErrorMessageVisible(true) + , formula1(formula1) + , formula2(formula2) { - } DataValidationPrivate::DataValidationPrivate(const DataValidationPrivate &other) - :QSharedData(other) - , validationType(DataValidation::None), validationOperator(DataValidation::Between) - , errorStyle(DataValidation::Stop), allowBlank(false), isPromptMessageVisible(true) + : QSharedData(other) + , validationType(DataValidation::None) + , validationOperator(DataValidation::Between) + , errorStyle(DataValidation::Stop) + , allowBlank(false) + , isPromptMessageVisible(true) , isErrorMessageVisible(true) { - } DataValidationPrivate::~DataValidationPrivate() { - } /*! @@ -83,7 +93,8 @@ DataValidationPrivate::~DataValidationPrivate() * \value Date restricts the cell to date values. * \value Time restricts the cell to time values. * \value TextLength restricts the cell data based on an integer string length. - * \value Custom restricts the cell based on an external Excel formula that returns a true/false value. + * \value Custom restricts the cell based on an external Excel formula that returns a true/false + * value. */ /*! @@ -117,28 +128,26 @@ DataValidationPrivate::~DataValidationPrivate() * Construct a data validation object with the given \a type, \a op, \a formula1 * \a formula2, and \a allowBlank. */ -DataValidation::DataValidation(ValidationType type, ValidationOperator op, const QString &formula1, const QString &formula2, bool allowBlank) - :d(new DataValidationPrivate(type, op, formula1, formula2, allowBlank)) +DataValidation::DataValidation(ValidationType type, ValidationOperator op, const QString &formula1, + const QString &formula2, bool allowBlank) + : d(new DataValidationPrivate(type, op, formula1, formula2, allowBlank)) { - } /*! Construct a data validation object */ DataValidation::DataValidation() - :d(new DataValidationPrivate()) + : d(new DataValidationPrivate()) { - } /*! Constructs a copy of \a other. */ DataValidation::DataValidation(const DataValidation &other) - :d(other.d) + : d(other.d) { - } /*! @@ -150,7 +159,6 @@ DataValidation &DataValidation::operator=(const DataValidation &other) return *this; } - /*! * Destroy the object. */ @@ -451,7 +459,7 @@ bool DataValidation::saveToXml(QXmlStreamWriter &writer) const if (!formula2().isEmpty()) writer.writeTextElement(QStringLiteral("formula2"), formula2()); - writer.writeEndElement(); //dataValidation + writer.writeEndElement(); // dataValidation return true; } @@ -535,8 +543,9 @@ DataValidation DataValidation::loadFromXml(QXmlStreamReader &reader) if (!p.isEmpty() || !pt.isEmpty()) validation.setPromptMessage(p, pt); - //find the end - while(!(reader.name() == QLatin1String("dataValidation") && reader.tokenType() == QXmlStreamReader::EndElement)) { + // find the end + while (!(reader.name() == QLatin1String("dataValidation") + && reader.tokenType() == QXmlStreamReader::EndElement)) { reader.readNextStartElement(); if (reader.tokenType() == QXmlStreamReader::StartElement) { if (reader.name() == QLatin1String("formula1")) { diff --git a/src/xlsx/xlsxdatavalidation.h b/src/xlsx/xlsxdatavalidation.h index 3a19079..d62a39c 100644 --- a/src/xlsx/xlsxdatavalidation.h +++ b/src/xlsx/xlsxdatavalidation.h @@ -43,20 +43,9 @@ class DataValidationPrivate; class Q_XLSX_EXPORT DataValidation { public: - enum ValidationType - { - None, - Whole, - Decimal, - List, - Date, - Time, - TextLength, - Custom - }; + enum ValidationType { None, Whole, Decimal, List, Date, Time, TextLength, Custom }; - enum ValidationOperator - { + enum ValidationOperator { Between, NotBetween, Equal, @@ -67,16 +56,12 @@ public: GreaterThanOrEqual }; - enum ErrorStyle - { - Stop, - Warning, - Information - }; + enum ErrorStyle { Stop, Warning, Information }; DataValidation(); - DataValidation(ValidationType type, ValidationOperator op=Between, const QString &formula1=QString() - , const QString &formula2=QString(), bool allowBlank=false); + DataValidation(ValidationType type, ValidationOperator op = Between, + const QString &formula1 = QString(), const QString &formula2 = QString(), + bool allowBlank = false); DataValidation(const DataValidation &other); ~DataValidation(); @@ -99,8 +84,8 @@ public: void setErrorStyle(ErrorStyle es); void setFormula1(const QString &formula); void setFormula2(const QString &formula); - void setErrorMessage(const QString &error, const QString &title=QString()); - void setPromptMessage(const QString &prompt, const QString &title=QString()); + void setErrorMessage(const QString &error, const QString &title = QString()); + void setPromptMessage(const QString &prompt, const QString &title = QString()); void setAllowBlank(bool enable); void setPromptMessageVisible(bool visible); void setErrorMessageVisible(bool visible); @@ -114,6 +99,7 @@ public: bool saveToXml(QXmlStreamWriter &writer) const; static DataValidation loadFromXml(QXmlStreamReader &reader); + private: QSharedDataPointer d; }; diff --git a/src/xlsx/xlsxdatavalidation_p.h b/src/xlsx/xlsxdatavalidation_p.h index 236bb3d..04e3caf 100644 --- a/src/xlsx/xlsxdatavalidation_p.h +++ b/src/xlsx/xlsxdatavalidation_p.h @@ -42,11 +42,13 @@ QT_BEGIN_NAMESPACE_XLSX -class Q_XLSX_EXPORT DataValidationPrivate : public QSharedData +class Q_XLSX_EXPORT DataValidationPrivate : public QSharedData { public: DataValidationPrivate(); - DataValidationPrivate(DataValidation::ValidationType type, DataValidation::ValidationOperator op, const QString &formula1, const QString &formula2, bool allowBlank); + DataValidationPrivate(DataValidation::ValidationType type, + DataValidation::ValidationOperator op, const QString &formula1, + const QString &formula2, bool allowBlank); DataValidationPrivate(const DataValidationPrivate &other); ~DataValidationPrivate(); diff --git a/src/xlsx/xlsxdocpropsapp.cpp b/src/xlsx/xlsxdocpropsapp.cpp index 49ad9b2..6f17cfe 100755 --- a/src/xlsx/xlsxdocpropsapp.cpp +++ b/src/xlsx/xlsxdocpropsapp.cpp @@ -35,7 +35,7 @@ namespace QXlsx { DocPropsApp::DocPropsApp(CreateFlag flag) - :AbstractOOXmlFile(flag) + : AbstractOOXmlFile(flag) { } @@ -83,11 +83,13 @@ QStringList DocPropsApp::propertyNames() const void DocPropsApp::saveToXmlFile(QIODevice *device) const { QXmlStreamWriter writer(device); - QString vt = QStringLiteral("http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"); + QString vt = + QStringLiteral("http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"); writer.writeStartDocument(QStringLiteral("1.0"), true); writer.writeStartElement(QStringLiteral("Properties")); - writer.writeDefaultNamespace(QStringLiteral("http://schemas.openxmlformats.org/officeDocument/2006/extended-properties")); + writer.writeDefaultNamespace(QStringLiteral( + "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties")); writer.writeNamespace(vt, QStringLiteral("vt")); writer.writeTextElement(QStringLiteral("Application"), QStringLiteral("Microsoft Excel")); writer.writeTextElement(QStringLiteral("DocSecurity"), QStringLiteral("0")); @@ -95,19 +97,19 @@ void DocPropsApp::saveToXmlFile(QIODevice *device) const writer.writeStartElement(QStringLiteral("HeadingPairs")); writer.writeStartElement(vt, QStringLiteral("vector")); - writer.writeAttribute(QStringLiteral("size"), QString::number(m_headingPairsList.size()*2)); + writer.writeAttribute(QStringLiteral("size"), QString::number(m_headingPairsList.size() * 2)); writer.writeAttribute(QStringLiteral("baseType"), QStringLiteral("variant")); - typedef QPair PairType; //Make foreach happy + typedef QPair PairType; // Make foreach happy foreach (PairType pair, m_headingPairsList) { writer.writeStartElement(vt, QStringLiteral("variant")); writer.writeTextElement(vt, QStringLiteral("lpstr"), pair.first); - writer.writeEndElement(); //vt:variant + writer.writeEndElement(); // vt:variant writer.writeStartElement(vt, QStringLiteral("variant")); writer.writeTextElement(vt, QStringLiteral("i4"), QString::number(pair.second)); - writer.writeEndElement(); //vt:variant + writer.writeEndElement(); // vt:variant } - writer.writeEndElement();//vt:vector - writer.writeEndElement();//HeadingPairs + writer.writeEndElement(); // vt:vector + writer.writeEndElement(); // HeadingPairs writer.writeStartElement(QStringLiteral("TitlesOfParts")); writer.writeStartElement(vt, QStringLiteral("vector")); @@ -115,19 +117,22 @@ void DocPropsApp::saveToXmlFile(QIODevice *device) const writer.writeAttribute(QStringLiteral("baseType"), QStringLiteral("lpstr")); foreach (QString title, m_titlesOfPartsList) writer.writeTextElement(vt, QStringLiteral("lpstr"), title); - writer.writeEndElement();//vt:vector - writer.writeEndElement();//TitlesOfParts + writer.writeEndElement(); // vt:vector + writer.writeEndElement(); // TitlesOfParts if (m_properties.contains(QStringLiteral("manager"))) writer.writeTextElement(QStringLiteral("Manager"), m_properties[QStringLiteral("manager")]); - //Not like "manager", "company" always exists for Excel generated file. - writer.writeTextElement(QStringLiteral("Company"), m_properties.contains(QStringLiteral("company")) ? m_properties[QStringLiteral("company")]: QString()); + // Not like "manager", "company" always exists for Excel generated file. + writer.writeTextElement(QStringLiteral("Company"), + m_properties.contains(QStringLiteral("company")) + ? m_properties[QStringLiteral("company")] + : QString()); writer.writeTextElement(QStringLiteral("LinksUpToDate"), QStringLiteral("false")); writer.writeTextElement(QStringLiteral("SharedDoc"), QStringLiteral("false")); writer.writeTextElement(QStringLiteral("HyperlinksChanged"), QStringLiteral("false")); writer.writeTextElement(QStringLiteral("AppVersion"), QStringLiteral("12.0000")); - writer.writeEndElement(); //Properties + writer.writeEndElement(); // Properties writer.writeEndDocument(); } @@ -135,23 +140,23 @@ bool DocPropsApp::loadFromXmlFile(QIODevice *device) { QXmlStreamReader reader(device); while (!reader.atEnd()) { - QXmlStreamReader::TokenType token = reader.readNext(); - if (token == QXmlStreamReader::StartElement) { - if (reader.name() == QLatin1String("Properties")) - continue; + QXmlStreamReader::TokenType token = reader.readNext(); + if (token == QXmlStreamReader::StartElement) { + if (reader.name() == QLatin1String("Properties")) + continue; - if (reader.name() == QStringLiteral("Manager")) { - setProperty(QStringLiteral("manager"), reader.readElementText()); - } else if (reader.name() == QStringLiteral("Company")) { - setProperty(QStringLiteral("company"), reader.readElementText()); - } - } + if (reader.name() == QStringLiteral("Manager")) { + setProperty(QStringLiteral("manager"), reader.readElementText()); + } else if (reader.name() == QStringLiteral("Company")) { + setProperty(QStringLiteral("company"), reader.readElementText()); + } + } - if (reader.hasError()) { - qDebug("Error when read doc props app file."); - } + if (reader.hasError()) { + qDebug("Error when read doc props app file."); + } } return true; } -} //namespace +} // namespace diff --git a/src/xlsx/xlsxdocpropsapp_p.h b/src/xlsx/xlsxdocpropsapp_p.h index 433731e..a32038c 100755 --- a/src/xlsx/xlsxdocpropsapp_p.h +++ b/src/xlsx/xlsxdocpropsapp_p.h @@ -51,7 +51,7 @@ class XLSX_AUTOTEST_EXPORT DocPropsApp : public AbstractOOXmlFile { public: DocPropsApp(CreateFlag flag); - + void addPartTitle(const QString &title); void addHeadingPair(const QString &name, int value); @@ -64,9 +64,8 @@ public: private: QStringList m_titlesOfPartsList; - QList > m_headingPairsList; + QList> m_headingPairsList; QMap m_properties; }; - } #endif // XLSXDOCPROPSAPP_H diff --git a/src/xlsx/xlsxdocpropscore.cpp b/src/xlsx/xlsxdocpropscore.cpp index 7e955f8..b0a20aa 100644 --- a/src/xlsx/xlsxdocpropscore.cpp +++ b/src/xlsx/xlsxdocpropscore.cpp @@ -35,7 +35,7 @@ namespace QXlsx { DocPropsCore::DocPropsCore(CreateFlag flag) - :AbstractOOXmlFile(flag) + : AbstractOOXmlFile(flag) { } @@ -76,7 +76,8 @@ QStringList DocPropsCore::propertyNames() const void DocPropsCore::saveToXmlFile(QIODevice *device) const { QXmlStreamWriter writer(device); - const QString cp = QStringLiteral("http://schemas.openxmlformats.org/package/2006/metadata/core-properties"); + const QString cp = + QStringLiteral("http://schemas.openxmlformats.org/package/2006/metadata/core-properties"); const QString dc = QStringLiteral("http://purl.org/dc/elements/1.1/"); const QString dcterms = QStringLiteral("http://purl.org/dc/terms/"); const QString dcmitype = QStringLiteral("http://purl.org/dc/dcmitype/"); @@ -93,35 +94,48 @@ void DocPropsCore::saveToXmlFile(QIODevice *device) const writer.writeTextElement(dc, QStringLiteral("title"), m_properties[QStringLiteral("title")]); if (m_properties.contains(QStringLiteral("subject"))) - writer.writeTextElement(dc, QStringLiteral("subject"), m_properties[QStringLiteral("subject")]); + writer.writeTextElement(dc, QStringLiteral("subject"), + m_properties[QStringLiteral("subject")]); - writer.writeTextElement(dc, QStringLiteral("creator"), m_properties.contains(QStringLiteral("creator")) ? m_properties[QStringLiteral("creator")] : QStringLiteral("Qt Xlsx Library")); + writer.writeTextElement(dc, QStringLiteral("creator"), + m_properties.contains(QStringLiteral("creator")) + ? m_properties[QStringLiteral("creator")] + : QStringLiteral("Qt Xlsx Library")); if (m_properties.contains(QStringLiteral("keywords"))) - writer.writeTextElement(cp, QStringLiteral("keywords"), m_properties[QStringLiteral("keywords")]); + writer.writeTextElement(cp, QStringLiteral("keywords"), + m_properties[QStringLiteral("keywords")]); if (m_properties.contains(QStringLiteral("description"))) - writer.writeTextElement(dc, QStringLiteral("description"), m_properties[QStringLiteral("description")]); + writer.writeTextElement(dc, QStringLiteral("description"), + m_properties[QStringLiteral("description")]); - writer.writeTextElement(cp, QStringLiteral("lastModifiedBy"), m_properties.contains(QStringLiteral("creator")) ? m_properties[QStringLiteral("creator")] : QStringLiteral("Qt Xlsx Library")); + writer.writeTextElement(cp, QStringLiteral("lastModifiedBy"), + m_properties.contains(QStringLiteral("creator")) + ? m_properties[QStringLiteral("creator")] + : QStringLiteral("Qt Xlsx Library")); writer.writeStartElement(dcterms, QStringLiteral("created")); writer.writeAttribute(xsi, QStringLiteral("type"), QStringLiteral("dcterms:W3CDTF")); - writer.writeCharacters(m_properties.contains(QStringLiteral("created")) ? m_properties[QStringLiteral("created")] : QDateTime::currentDateTime().toString(Qt::ISODate)); - writer.writeEndElement();//dcterms:created + writer.writeCharacters(m_properties.contains(QStringLiteral("created")) + ? m_properties[QStringLiteral("created")] + : QDateTime::currentDateTime().toString(Qt::ISODate)); + writer.writeEndElement(); // dcterms:created writer.writeStartElement(dcterms, QStringLiteral("modified")); writer.writeAttribute(xsi, QStringLiteral("type"), QStringLiteral("dcterms:W3CDTF")); writer.writeCharacters(QDateTime::currentDateTime().toString(Qt::ISODate)); - writer.writeEndElement();//dcterms:created + writer.writeEndElement(); // dcterms:created if (m_properties.contains(QStringLiteral("category"))) - writer.writeTextElement(cp, QStringLiteral("category"), m_properties[QStringLiteral("category")]); + writer.writeTextElement(cp, QStringLiteral("category"), + m_properties[QStringLiteral("category")]); if (m_properties.contains(QStringLiteral("status"))) - writer.writeTextElement(cp, QStringLiteral("contentStatus"), m_properties[QStringLiteral("status")]); + writer.writeTextElement(cp, QStringLiteral("contentStatus"), + m_properties[QStringLiteral("status")]); - writer.writeEndElement(); //cp:coreProperties + writer.writeEndElement(); // cp:coreProperties writer.writeEndDocument(); } @@ -129,40 +143,40 @@ bool DocPropsCore::loadFromXmlFile(QIODevice *device) { QXmlStreamReader reader(device); - const QString cp = QStringLiteral("http://schemas.openxmlformats.org/package/2006/metadata/core-properties"); + const QString cp = + QStringLiteral("http://schemas.openxmlformats.org/package/2006/metadata/core-properties"); const QString dc = QStringLiteral("http://purl.org/dc/elements/1.1/"); const QString dcterms = QStringLiteral("http://purl.org/dc/terms/"); while (!reader.atEnd()) { - QXmlStreamReader::TokenType token = reader.readNext(); - if (token == QXmlStreamReader::StartElement) { - const QStringRef nsUri = reader.namespaceUri(); - const QStringRef name = reader.name(); - if (name == QStringLiteral("subject") && nsUri == dc) { - setProperty(QStringLiteral("subject"), reader.readElementText()); - } else if (name == QStringLiteral("title") && nsUri == dc) { - setProperty(QStringLiteral("title"), reader.readElementText()); - } else if (name == QStringLiteral("creator") && nsUri == dc) { - setProperty(QStringLiteral("creator"), reader.readElementText()); - } else if (name == QStringLiteral("description") && nsUri == dc) { - setProperty(QStringLiteral("description"), reader.readElementText()); - } else if (name == QStringLiteral("keywords") && nsUri == cp) { - setProperty(QStringLiteral("keywords"), reader.readElementText()); - } else if (name == QStringLiteral("created") && nsUri == dcterms) { - setProperty(QStringLiteral("created"), reader.readElementText()); - } else if (name == QStringLiteral("category") && nsUri == cp) { - setProperty(QStringLiteral("category"), reader.readElementText()); - } else if (name == QStringLiteral("contentStatus") && nsUri == cp) { - setProperty(QStringLiteral("status"), reader.readElementText()); - } - } + QXmlStreamReader::TokenType token = reader.readNext(); + if (token == QXmlStreamReader::StartElement) { + const QStringRef nsUri = reader.namespaceUri(); + const QStringRef name = reader.name(); + if (name == QStringLiteral("subject") && nsUri == dc) { + setProperty(QStringLiteral("subject"), reader.readElementText()); + } else if (name == QStringLiteral("title") && nsUri == dc) { + setProperty(QStringLiteral("title"), reader.readElementText()); + } else if (name == QStringLiteral("creator") && nsUri == dc) { + setProperty(QStringLiteral("creator"), reader.readElementText()); + } else if (name == QStringLiteral("description") && nsUri == dc) { + setProperty(QStringLiteral("description"), reader.readElementText()); + } else if (name == QStringLiteral("keywords") && nsUri == cp) { + setProperty(QStringLiteral("keywords"), reader.readElementText()); + } else if (name == QStringLiteral("created") && nsUri == dcterms) { + setProperty(QStringLiteral("created"), reader.readElementText()); + } else if (name == QStringLiteral("category") && nsUri == cp) { + setProperty(QStringLiteral("category"), reader.readElementText()); + } else if (name == QStringLiteral("contentStatus") && nsUri == cp) { + setProperty(QStringLiteral("status"), reader.readElementText()); + } + } - if (reader.hasError()) { - qDebug()<<"Error when read doc props core file."< m_properties; }; - } #endif // XLSXDOCPROPSCORE_H diff --git a/src/xlsx/xlsxdocument.cpp b/src/xlsx/xlsxdocument.cpp index 314e789..3bfcb7e 100644 --- a/src/xlsx/xlsxdocument.cpp +++ b/src/xlsx/xlsxdocument.cpp @@ -84,15 +84,17 @@ QT_BEGIN_NAMESPACE_XLSX elements of the package and writes them into the XLSX file. */ -DocumentPrivate::DocumentPrivate(Document *p) : - q_ptr(p), defaultPackageName(QStringLiteral("Book1.xlsx")) +DocumentPrivate::DocumentPrivate(Document *p) + : q_ptr(p) + , defaultPackageName(QStringLiteral("Book1.xlsx")) { } void DocumentPrivate::init() { if (contentTypes.isNull()) - contentTypes = QSharedPointer(new ContentTypes(ContentTypes::F_NewFromScratch)); + contentTypes = + QSharedPointer(new ContentTypes(ContentTypes::F_NewFromScratch)); if (workbook.isNull()) workbook = QSharedPointer(new Workbook(Workbook::F_NewFromScratch)); @@ -104,23 +106,24 @@ bool DocumentPrivate::loadPackage(QIODevice *device) ZipReader zipReader(device); QStringList filePaths = zipReader.filePaths(); - //Load the Content_Types file + // Load the Content_Types file if (!filePaths.contains(QLatin1String("[Content_Types].xml"))) return false; contentTypes = QSharedPointer(new ContentTypes(ContentTypes::F_LoadFromExists)); contentTypes->loadFromXmlData(zipReader.fileData(QStringLiteral("[Content_Types].xml"))); - //Load root rels file + // Load root rels file if (!filePaths.contains(QLatin1String("_rels/.rels"))) return false; Relationships rootRels; rootRels.loadFromXmlData(zipReader.fileData(QStringLiteral("_rels/.rels"))); - //load core property - QList rels_core = rootRels.packageRelationships(QStringLiteral("/metadata/core-properties")); + // load core property + QList rels_core = + rootRels.packageRelationships(QStringLiteral("/metadata/core-properties")); if (!rels_core.isEmpty()) { - //Get the core property file name if it exists. - //In normal case, this should be "docProps/core.xml" + // Get the core property file name if it exists. + // In normal case, this should be "docProps/core.xml" QString docPropsCore_Name = rels_core[0].target; DocPropsCore props(DocPropsCore::F_LoadFromExists); @@ -129,11 +132,12 @@ bool DocumentPrivate::loadPackage(QIODevice *device) q->setDocumentProperty(name, props.property(name)); } - //load app property - QList rels_app = rootRels.documentRelationships(QStringLiteral("/extended-properties")); + // load app property + QList rels_app = + rootRels.documentRelationships(QStringLiteral("/extended-properties")); if (!rels_app.isEmpty()) { - //Get the app property file name if it exists. - //In normal case, this should be "docProps/app.xml" + // Get the app property file name if it exists. + // In normal case, this should be "docProps/app.xml" QString docPropsApp_Name = rels_app[0].target; DocPropsApp props(DocPropsApp::F_LoadFromExists); @@ -142,10 +146,11 @@ bool DocumentPrivate::loadPackage(QIODevice *device) q->setDocumentProperty(name, props.property(name)); } - //load workbook now, Get the workbook file path from the root rels file - //In normal case, this should be "xl/workbook.xml" + // load workbook now, Get the workbook file path from the root rels file + // In normal case, this should be "xl/workbook.xml" workbook = QSharedPointer(new Workbook(Workbook::F_LoadFromExists)); - QList rels_xl = rootRels.documentRelationships(QStringLiteral("/officeDocument")); + QList rels_xl = + rootRels.documentRelationships(QStringLiteral("/officeDocument")); if (rels_xl.isEmpty()) return false; QString xlworkbook_Path = rels_xl[0].target; @@ -154,57 +159,60 @@ bool DocumentPrivate::loadPackage(QIODevice *device) workbook->setFilePath(xlworkbook_Path); workbook->loadFromXmlData(zipReader.fileData(xlworkbook_Path)); - //load styles - QList rels_styles = workbook->relationships()->documentRelationships(QStringLiteral("/styles")); + // load styles + QList rels_styles = + workbook->relationships()->documentRelationships(QStringLiteral("/styles")); if (!rels_styles.isEmpty()) { - //In normal case this should be styles.xml which in xl + // In normal case this should be styles.xml which in xl QString name = rels_styles[0].target; QString path = xlworkbook_Dir + QLatin1String("/") + name; - QSharedPointer styles (new Styles(Styles::F_LoadFromExists)); + QSharedPointer styles(new Styles(Styles::F_LoadFromExists)); styles->loadFromXmlData(zipReader.fileData(path)); workbook->d_func()->styles = styles; } - //load sharedStrings - QList rels_sharedStrings = workbook->relationships()->documentRelationships(QStringLiteral("/sharedStrings")); + // load sharedStrings + QList rels_sharedStrings = + workbook->relationships()->documentRelationships(QStringLiteral("/sharedStrings")); if (!rels_sharedStrings.isEmpty()) { - //In normal case this should be sharedStrings.xml which in xl + // In normal case this should be sharedStrings.xml which in xl QString name = rels_sharedStrings[0].target; QString path = xlworkbook_Dir + QLatin1String("/") + name; workbook->d_func()->sharedStrings->loadFromXmlData(zipReader.fileData(path)); } - //load theme - QList rels_theme = workbook->relationships()->documentRelationships(QStringLiteral("/theme")); + // load theme + QList rels_theme = + workbook->relationships()->documentRelationships(QStringLiteral("/theme")); if (!rels_theme.isEmpty()) { - //In normal case this should be theme/theme1.xml which in xl + // In normal case this should be theme/theme1.xml which in xl QString name = rels_theme[0].target; QString path = xlworkbook_Dir + QLatin1String("/") + name; workbook->theme()->loadFromXmlData(zipReader.fileData(path)); } - //load sheets - for (int i=0; isheetCount(); ++i) { + // load sheets + for (int i = 0; i < workbook->sheetCount(); ++i) { AbstractSheet *sheet = workbook->sheet(i); QString rel_path = getRelFilePath(sheet->filePath()); - //If the .rel file exists, load it. + // If the .rel file exists, load it. if (zipReader.filePaths().contains(rel_path)) sheet->relationships()->loadFromXmlData(zipReader.fileData(rel_path)); sheet->loadFromXmlData(zipReader.fileData(sheet->filePath())); } - //load external links - for (int i=0; id_func()->externalLinks.count(); ++i) { + // load external links + for (int i = 0; i < workbook->d_func()->externalLinks.count(); ++i) { SimpleOOXmlFile *link = workbook->d_func()->externalLinks[i].data(); QString rel_path = getRelFilePath(link->filePath()); - //If the .rel file exists, load it. + // If the .rel file exists, load it. if (zipReader.filePaths().contains(rel_path)) link->relationships()->loadFromXmlData(zipReader.fileData(rel_path)); link->loadFromXmlData(zipReader.fileData(link->filePath())); } - //load drawings - for (int i=0; idrawings().size(); ++i) { + // load drawings + for (int i = 0; i < workbook->drawings().size(); ++i) { Drawing *drawing = workbook->drawings()[i]; QString rel_path = getRelFilePath(drawing->filePath()); if (zipReader.filePaths().contains(rel_path)) @@ -212,19 +220,19 @@ bool DocumentPrivate::loadPackage(QIODevice *device) drawing->loadFromXmlData(zipReader.fileData(drawing->filePath())); } - //load charts - QList > chartFileToLoad = workbook->chartFiles(); - for (int i=0; i> chartFileToLoad = workbook->chartFiles(); + for (int i = 0; i < chartFileToLoad.size(); ++i) { QSharedPointer cf = chartFileToLoad[i]; cf->loadFromXmlData(zipReader.fileData(cf->filePath())); } - //load media files - QList > mediaFileToLoad = workbook->mediaFiles(); - for (int i=0; i> mediaFileToLoad = workbook->mediaFiles(); + for (int i = 0; i < mediaFileToLoad.size(); ++i) { QSharedPointer mf = mediaFileToLoad[i]; const QString path = mf->fileName(); - const QString suffix = path.mid(path.lastIndexOf(QLatin1Char('.'))+1); + const QString suffix = path.mid(path.lastIndexOf(QLatin1Char('.')) + 1); mf->set(zipReader.fileData(path), suffix); } @@ -244,59 +252,71 @@ bool DocumentPrivate::savePackage(QIODevice *device) const DocPropsCore docPropsCore(DocPropsCore::F_NewFromScratch); // save worksheet xml files - QList > worksheets = workbook->getSheetsByTypes(AbstractSheet::ST_WorkSheet); + QList> worksheets = + workbook->getSheetsByTypes(AbstractSheet::ST_WorkSheet); if (!worksheets.isEmpty()) docPropsApp.addHeadingPair(QStringLiteral("Worksheets"), worksheets.size()); - for (int i=0; i sheet = worksheets[i]; - contentTypes->addWorksheetName(QStringLiteral("sheet%1").arg(i+1)); + contentTypes->addWorksheetName(QStringLiteral("sheet%1").arg(i + 1)); docPropsApp.addPartTitle(sheet->sheetName()); - zipWriter.addFile(QStringLiteral("xl/worksheets/sheet%1.xml").arg(i+1), sheet->saveToXmlData()); + zipWriter.addFile(QStringLiteral("xl/worksheets/sheet%1.xml").arg(i + 1), + sheet->saveToXmlData()); Relationships *rel = sheet->relationships(); if (!rel->isEmpty()) - zipWriter.addFile(QStringLiteral("xl/worksheets/_rels/sheet%1.xml.rels").arg(i+1), rel->saveToXmlData()); + zipWriter.addFile(QStringLiteral("xl/worksheets/_rels/sheet%1.xml.rels").arg(i + 1), + rel->saveToXmlData()); } - //save chartsheet xml files - QList > chartsheets = workbook->getSheetsByTypes(AbstractSheet::ST_ChartSheet); + // save chartsheet xml files + QList> chartsheets = + workbook->getSheetsByTypes(AbstractSheet::ST_ChartSheet); if (!chartsheets.isEmpty()) docPropsApp.addHeadingPair(QStringLiteral("Chartsheets"), chartsheets.size()); - for (int i=0; i sheet = chartsheets[i]; - contentTypes->addWorksheetName(QStringLiteral("sheet%1").arg(i+1)); + contentTypes->addWorksheetName(QStringLiteral("sheet%1").arg(i + 1)); docPropsApp.addPartTitle(sheet->sheetName()); - zipWriter.addFile(QStringLiteral("xl/chartsheets/sheet%1.xml").arg(i+1), sheet->saveToXmlData()); + zipWriter.addFile(QStringLiteral("xl/chartsheets/sheet%1.xml").arg(i + 1), + sheet->saveToXmlData()); Relationships *rel = sheet->relationships(); if (!rel->isEmpty()) - zipWriter.addFile(QStringLiteral("xl/chartsheets/_rels/sheet%1.xml.rels").arg(i+1), rel->saveToXmlData()); + zipWriter.addFile(QStringLiteral("xl/chartsheets/_rels/sheet%1.xml.rels").arg(i + 1), + rel->saveToXmlData()); } // save external links xml files - for (int i=0; id_func()->externalLinks.count(); ++i) { + for (int i = 0; i < workbook->d_func()->externalLinks.count(); ++i) { SimpleOOXmlFile *link = workbook->d_func()->externalLinks[i].data(); - contentTypes->addExternalLinkName(QStringLiteral("externalLink%1").arg(i+1)); + contentTypes->addExternalLinkName(QStringLiteral("externalLink%1").arg(i + 1)); - zipWriter.addFile(QStringLiteral("xl/externalLinks/externalLink%1.xml").arg(i+1), link->saveToXmlData()); + zipWriter.addFile(QStringLiteral("xl/externalLinks/externalLink%1.xml").arg(i + 1), + link->saveToXmlData()); Relationships *rel = link->relationships(); if (!rel->isEmpty()) - zipWriter.addFile(QStringLiteral("xl/externalLinks/_rels/externalLink%1.xml.rels").arg(i+1), rel->saveToXmlData()); + zipWriter.addFile( + QStringLiteral("xl/externalLinks/_rels/externalLink%1.xml.rels").arg(i + 1), + rel->saveToXmlData()); } // save workbook xml file contentTypes->addWorkbook(); zipWriter.addFile(QStringLiteral("xl/workbook.xml"), workbook->saveToXmlData()); - zipWriter.addFile(QStringLiteral("xl/_rels/workbook.xml.rels"), workbook->relationships()->saveToXmlData()); + zipWriter.addFile(QStringLiteral("xl/_rels/workbook.xml.rels"), + workbook->relationships()->saveToXmlData()); // save drawing xml files - for (int i=0; idrawings().size(); ++i) { - contentTypes->addDrawingName(QStringLiteral("drawing%1").arg(i+1)); + for (int i = 0; i < workbook->drawings().size(); ++i) { + contentTypes->addDrawingName(QStringLiteral("drawing%1").arg(i + 1)); Drawing *drawing = workbook->drawings()[i]; - zipWriter.addFile(QStringLiteral("xl/drawings/drawing%1.xml").arg(i+1), drawing->saveToXmlData()); + zipWriter.addFile(QStringLiteral("xl/drawings/drawing%1.xml").arg(i + 1), + drawing->saveToXmlData()); if (!drawing->relationships()->isEmpty()) - zipWriter.addFile(QStringLiteral("xl/drawings/_rels/drawing%1.xml.rels").arg(i+1), drawing->relationships()->saveToXmlData()); + zipWriter.addFile(QStringLiteral("xl/drawings/_rels/drawing%1.xml.rels").arg(i + 1), + drawing->relationships()->saveToXmlData()); } // save docProps app/core xml file @@ -312,7 +332,8 @@ bool DocumentPrivate::savePackage(QIODevice *device) const // save sharedStrings xml file if (!workbook->sharedStrings()->isEmpty()) { contentTypes->addSharedString(); - zipWriter.addFile(QStringLiteral("xl/sharedStrings.xml"), workbook->sharedStrings()->saveToXmlData()); + zipWriter.addFile(QStringLiteral("xl/sharedStrings.xml"), + workbook->sharedStrings()->saveToXmlData()); } // save styles xml file @@ -324,26 +345,30 @@ bool DocumentPrivate::savePackage(QIODevice *device) const zipWriter.addFile(QStringLiteral("xl/theme/theme1.xml"), workbook->theme()->saveToXmlData()); // save chart xml files - for (int i=0; ichartFiles().size(); ++i) { - contentTypes->addChartName(QStringLiteral("chart%1").arg(i+1)); + for (int i = 0; i < workbook->chartFiles().size(); ++i) { + contentTypes->addChartName(QStringLiteral("chart%1").arg(i + 1)); QSharedPointer cf = workbook->chartFiles()[i]; - zipWriter.addFile(QStringLiteral("xl/charts/chart%1.xml").arg(i+1), cf->saveToXmlData()); + zipWriter.addFile(QStringLiteral("xl/charts/chart%1.xml").arg(i + 1), cf->saveToXmlData()); } // save image files - for (int i=0; imediaFiles().size(); ++i) { + for (int i = 0; i < workbook->mediaFiles().size(); ++i) { QSharedPointer mf = workbook->mediaFiles()[i]; if (!mf->mimeType().isEmpty()) contentTypes->addDefault(mf->suffix(), mf->mimeType()); - zipWriter.addFile(QStringLiteral("xl/media/image%1.%2").arg(i+1).arg(mf->suffix()), mf->contents()); + zipWriter.addFile(QStringLiteral("xl/media/image%1.%2").arg(i + 1).arg(mf->suffix()), + mf->contents()); } // save root .rels xml file Relationships rootrels; - rootrels.addDocumentRelationship(QStringLiteral("/officeDocument"), QStringLiteral("xl/workbook.xml")); - rootrels.addPackageRelationship(QStringLiteral("/metadata/core-properties"), QStringLiteral("docProps/core.xml")); - rootrels.addDocumentRelationship(QStringLiteral("/extended-properties"), QStringLiteral("docProps/app.xml")); + rootrels.addDocumentRelationship(QStringLiteral("/officeDocument"), + QStringLiteral("xl/workbook.xml")); + rootrels.addPackageRelationship(QStringLiteral("/metadata/core-properties"), + QStringLiteral("docProps/core.xml")); + rootrels.addDocumentRelationship(QStringLiteral("/extended-properties"), + QStringLiteral("docProps/app.xml")); zipWriter.addFile(QStringLiteral("_rels/.rels"), rootrels.saveToXmlData()); // save content types xml file @@ -353,7 +378,6 @@ bool DocumentPrivate::savePackage(QIODevice *device) const return true; } - /*! \class Document \inmodule QtXlsx @@ -365,8 +389,9 @@ bool DocumentPrivate::savePackage(QIODevice *device) const * Creates a new empty xlsx document. * The \a parent argument is passed to QObject's constructor. */ -Document::Document(QObject *parent) : - QObject(parent), d_ptr(new DocumentPrivate(this)) +Document::Document(QObject *parent) + : QObject(parent) + , d_ptr(new DocumentPrivate(this)) { d_ptr->init(); } @@ -376,8 +401,9 @@ Document::Document(QObject *parent) : * Try to open an existing xlsx document named \a name. * The \a parent argument is passed to QObject's constructor. */ -Document::Document(const QString &name, QObject *parent) : - QObject(parent), d_ptr(new DocumentPrivate(this)) +Document::Document(const QString &name, QObject *parent) + : QObject(parent) + , d_ptr(new DocumentPrivate(this)) { d_ptr->packageName = name; if (QFile::exists(name)) { @@ -393,8 +419,9 @@ Document::Document(const QString &name, QObject *parent) : * Try to open an existing xlsx document from \a device. * The \a parent argument is passed to QObject's constructor. */ -Document::Document(QIODevice *device, QObject *parent) : - QObject(parent), d_ptr(new DocumentPrivate(this)) +Document::Document(QIODevice *device, QObject *parent) + : QObject(parent) + , d_ptr(new DocumentPrivate(this)) { if (device && device->isReadable()) d_ptr->loadPackage(device); @@ -537,7 +564,7 @@ bool Document::setColumnHidden(const CellRange &range, bool hidden) */ bool Document::setColumnWidth(int column, double width) { - return setColumnWidth(column,column,width); + return setColumnWidth(column, column, width); } /*! @@ -546,7 +573,7 @@ bool Document::setColumnWidth(int column, double width) */ bool Document::setColumnFormat(int column, const Format &format) { - return setColumnFormat(column,column,format); + return setColumnFormat(column, column, format); } /*! @@ -555,7 +582,7 @@ bool Document::setColumnFormat(int column, const Format &format) */ bool Document::setColumnHidden(int column, bool hidden) { - return setColumnHidden(column,column,hidden); + return setColumnHidden(column, column, hidden); } /*! @@ -581,7 +608,6 @@ bool Document::setColumnFormat(int colFirst, int colLast, const Format &format) return false; } - /*! Sets hidden property of columns [\a colFirst, \a colLast] to \a hidden. Columns are 1-indexed. @@ -602,7 +628,7 @@ bool Document::setColumnHidden(int colFirst, int colLast, bool hidden) double Document::columnWidth(int column) { if (Worksheet *sheet = currentWorksheet()) - return sheet->columnWidth(column); + return sheet->columnWidth(column); return 0.0; } @@ -612,7 +638,7 @@ double Document::columnWidth(int column) Format Document::columnFormat(int column) { if (Worksheet *sheet = currentWorksheet()) - return sheet->columnFormat(column); + return sheet->columnFormat(column); return Format(); } @@ -622,7 +648,7 @@ Format Document::columnFormat(int column) bool Document::isColumnHidden(int column) { if (Worksheet *sheet = currentWorksheet()) - return sheet->isColumnHidden(column); + return sheet->isColumnHidden(column); return false; } @@ -634,7 +660,7 @@ bool Document::isColumnHidden(int column) */ bool Document::setRowFormat(int row, const Format &format) { - return setRowFormat(row,row, format); + return setRowFormat(row, row, format); } /*! @@ -646,7 +672,7 @@ bool Document::setRowFormat(int row, const Format &format) bool Document::setRowFormat(int rowFirst, int rowLast, const Format &format) { if (Worksheet *sheet = currentWorksheet()) - return sheet->setRowFormat(rowFirst, rowLast, format); + return sheet->setRowFormat(rowFirst, rowLast, format); return false; } @@ -658,7 +684,7 @@ bool Document::setRowFormat(int rowFirst, int rowLast, const Format &format) */ bool Document::setRowHidden(int row, bool hidden) { - return setRowHidden(row,row,hidden); + return setRowHidden(row, row, hidden); } /*! @@ -670,7 +696,7 @@ bool Document::setRowHidden(int row, bool hidden) bool Document::setRowHidden(int rowFirst, int rowLast, bool hidden) { if (Worksheet *sheet = currentWorksheet()) - return sheet->setRowHidden(rowFirst, rowLast, hidden); + return sheet->setRowHidden(rowFirst, rowLast, hidden); return false; } @@ -683,7 +709,7 @@ bool Document::setRowHidden(int rowFirst, int rowLast, bool hidden) */ bool Document::setRowHeight(int row, double height) { - return setRowHeight(row,row,height); + return setRowHeight(row, row, height); } /*! @@ -696,7 +722,7 @@ bool Document::setRowHeight(int row, double height) bool Document::setRowHeight(int rowFirst, int rowLast, double height) { if (Worksheet *sheet = currentWorksheet()) - return sheet->setRowHeight(rowFirst, rowLast, height); + return sheet->setRowHeight(rowFirst, rowLast, height); return false; } @@ -705,8 +731,8 @@ bool Document::setRowHeight(int rowFirst, int rowLast, double height) */ double Document::rowHeight(int row) { - if (Worksheet *sheet = currentWorksheet()) - return sheet->rowHeight(row); + if (Worksheet *sheet = currentWorksheet()) + return sheet->rowHeight(row); return 0.0; } @@ -716,8 +742,8 @@ double Document::rowHeight(int row) Format Document::rowFormat(int row) { if (Worksheet *sheet = currentWorksheet()) - return sheet->rowFormat(row); - return Format(); + return sheet->rowFormat(row); + return Format(); } /*! @@ -726,8 +752,8 @@ Format Document::rowFormat(int row) bool Document::isRowHidden(int row) { if (Worksheet *sheet = currentWorksheet()) - return sheet->isRowHidden(row); - return false; + return sheet->isRowHidden(row); + return false; } /*! @@ -808,7 +834,8 @@ Cell *Document::cellAt(int row, int col) const * \param scope The name of one worksheet, or empty which means golbal scope. * \return Return false if the name invalid. */ -bool Document::defineName(const QString &name, const QString &formula, const QString &comment, const QString &scope) +bool Document::defineName(const QString &name, const QString &formula, const QString &comment, + const QString &scope) { Q_D(Document); diff --git a/src/xlsx/xlsxdocument.h b/src/xlsx/xlsxdocument.h index 7f1113d..7819571 100644 --- a/src/xlsx/xlsxdocument.h +++ b/src/xlsx/xlsxdocument.h @@ -52,17 +52,17 @@ class Q_XLSX_EXPORT Document : public QObject public: explicit Document(QObject *parent = 0); - Document(const QString &xlsxName, QObject *parent=0); - Document(QIODevice *device, QObject *parent=0); + Document(const QString &xlsxName, QObject *parent = 0); + Document(QIODevice *device, QObject *parent = 0); ~Document(); - bool write(const CellReference &cell, const QVariant &value, const Format &format=Format()); - bool write(int row, int col, const QVariant &value, const Format &format=Format()); + bool write(const CellReference &cell, const QVariant &value, const Format &format = Format()); + bool write(int row, int col, const QVariant &value, const Format &format = Format()); QVariant read(const CellReference &cell) const; QVariant read(int row, int col) const; bool insertImage(int row, int col, const QImage &image); Chart *insertChart(int row, int col, const QSize &size); - bool mergeCells(const CellRange &range, const Format &format=Format()); + bool mergeCells(const CellRange &range, const Format &format = Format()); bool unmergeCells(const CellRange &range); bool setColumnWidth(const CellRange &range, double width); @@ -97,7 +97,8 @@ public: Cell *cellAt(const CellReference &cell) const; Cell *cellAt(int row, int col) const; - bool defineName(const QString &name, const QString &formula, const QString &comment=QString(), const QString &scope=QString()); + bool defineName(const QString &name, const QString &formula, const QString &comment = QString(), + const QString &scope = QString()); CellRange dimension() const; @@ -106,8 +107,10 @@ public: QStringList documentPropertyNames() const; QStringList sheetNames() const; - bool addSheet(const QString &name = QString(), AbstractSheet::SheetType type = AbstractSheet::ST_WorkSheet); - bool insertSheet(int index, const QString &name = QString(), AbstractSheet::SheetType type = AbstractSheet::ST_WorkSheet); + bool addSheet(const QString &name = QString(), + AbstractSheet::SheetType type = AbstractSheet::ST_WorkSheet); + bool insertSheet(int index, const QString &name = QString(), + AbstractSheet::SheetType type = AbstractSheet::ST_WorkSheet); bool selectSheet(const QString &name); bool renameSheet(const QString &oldName, const QString &newName); bool copySheet(const QString &srcName, const QString &distName = QString()); @@ -125,7 +128,7 @@ public: private: Q_DISABLE_COPY(Document) - DocumentPrivate * const d_ptr; + DocumentPrivate *const d_ptr; }; QT_END_NAMESPACE_XLSX diff --git a/src/xlsx/xlsxdocument_p.h b/src/xlsx/xlsxdocument_p.h index 736a678..c2cc571 100644 --- a/src/xlsx/xlsxdocument_p.h +++ b/src/xlsx/xlsxdocument_p.h @@ -56,14 +56,13 @@ public: bool savePackage(QIODevice *device) const; Document *q_ptr; - const QString defaultPackageName; //default name when package name not specified - QString packageName; //name of the .xlsx file + const QString defaultPackageName; // default name when package name not specified + QString packageName; // name of the .xlsx file - QMap documentProperties; //core, app and custom properties + QMap documentProperties; // core, app and custom properties QSharedPointer workbook; QSharedPointer contentTypes; }; - } #endif // XLSXDOCUMENT_P_H diff --git a/src/xlsx/xlsxdrawing.cpp b/src/xlsx/xlsxdrawing.cpp index ae7d2d7..02edadb 100644 --- a/src/xlsx/xlsxdrawing.cpp +++ b/src/xlsx/xlsxdrawing.cpp @@ -34,7 +34,8 @@ namespace QXlsx { Drawing::Drawing(AbstractSheet *sheet, CreateFlag flag) - :AbstractOOXmlFile(flag), sheet(sheet) + : AbstractOOXmlFile(flag) + , sheet(sheet) { workbook = sheet->workbook(); } @@ -52,13 +53,16 @@ void Drawing::saveToXmlFile(QIODevice *device) const writer.writeStartDocument(QStringLiteral("1.0"), true); writer.writeStartElement(QStringLiteral("xdr:wsDr")); - writer.writeAttribute(QStringLiteral("xmlns:xdr"), QStringLiteral("http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing")); - writer.writeAttribute(QStringLiteral("xmlns:a"), QStringLiteral("http://schemas.openxmlformats.org/drawingml/2006/main")); + writer.writeAttribute( + QStringLiteral("xmlns:xdr"), + QStringLiteral("http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing")); + writer.writeAttribute(QStringLiteral("xmlns:a"), + QStringLiteral("http://schemas.openxmlformats.org/drawingml/2006/main")); foreach (DrawingAnchor *anchor, anchors) anchor->saveToXml(writer); - writer.writeEndElement();//xdr:wsDr + writer.writeEndElement(); // xdr:wsDr writer.writeEndDocument(); } @@ -69,13 +73,13 @@ bool Drawing::loadFromXmlFile(QIODevice *device) reader.readNextStartElement(); if (reader.tokenType() == QXmlStreamReader::StartElement) { if (reader.name() == QLatin1String("absoluteAnchor")) { - DrawingAbsoluteAnchor * anchor = new DrawingAbsoluteAnchor(this); + DrawingAbsoluteAnchor *anchor = new DrawingAbsoluteAnchor(this); anchor->loadFromXml(reader); } else if (reader.name() == QLatin1String("oneCellAnchor")) { - DrawingOneCellAnchor * anchor = new DrawingOneCellAnchor(this); + DrawingOneCellAnchor *anchor = new DrawingOneCellAnchor(this); anchor->loadFromXml(reader); } else if (reader.name() == QLatin1String("twoCellAnchor")) { - DrawingTwoCellAnchor * anchor = new DrawingTwoCellAnchor(this); + DrawingTwoCellAnchor *anchor = new DrawingTwoCellAnchor(this); anchor->loadFromXml(reader); } } diff --git a/src/xlsx/xlsxdrawinganchor.cpp b/src/xlsx/xlsxdrawinganchor.cpp index be12dc0..4992267 100644 --- a/src/xlsx/xlsxdrawinganchor.cpp +++ b/src/xlsx/xlsxdrawinganchor.cpp @@ -68,18 +68,18 @@ namespace QXlsx { variable and have to be taken into account. */ -//anchor +// anchor DrawingAnchor::DrawingAnchor(Drawing *drawing, ObjectType objectType) - :m_drawing(drawing), m_objectType(objectType) + : m_drawing(drawing) + , m_objectType(objectType) { m_drawing->anchors.append(this); - m_id = m_drawing->anchors.size();//must be unique in one drawing{x}.xml file. + m_id = m_drawing->anchors.size(); // must be unique in one drawing{x}.xml file. } DrawingAnchor::~DrawingAnchor() { - } void DrawingAnchor::setObjectPicture(const QImage &img) @@ -89,7 +89,8 @@ void DrawingAnchor::setObjectPicture(const QImage &img) buffer.open(QIODevice::WriteOnly); img.save(&buffer, "PNG"); - m_pictureFile = QSharedPointer(new MediaFile(ba, QStringLiteral("png"), QStringLiteral("image/png"))); + m_pictureFile = QSharedPointer( + new MediaFile(ba, QStringLiteral("png"), QStringLiteral("image/png"))); m_drawing->workbook->addMediaFile(m_pictureFile); m_objectType = Picture; @@ -145,8 +146,7 @@ XlsxMarker DrawingAnchor::loadXmlMarker(QXmlStreamReader &reader, const QString } else if (reader.name() == QLatin1String("rowOff")) { rowOffset = reader.readElementText().toInt(); } - } else if (reader.tokenType() == QXmlStreamReader::EndElement - && reader.name() == node) { + } else if (reader.tokenType() == QXmlStreamReader::EndElement && reader.name() == node) { break; } } @@ -157,23 +157,23 @@ XlsxMarker DrawingAnchor::loadXmlMarker(QXmlStreamReader &reader, const QString void DrawingAnchor::loadXmlObject(QXmlStreamReader &reader) { if (reader.name() == QLatin1String("sp")) { - //Shape + // Shape m_objectType = Shape; loadXmlObjectShape(reader); } else if (reader.name() == QLatin1String("grpSp")) { - //Group Shape + // Group Shape m_objectType = GroupShape; loadXmlObjectGroupShape(reader); } else if (reader.name() == QLatin1String("graphicFrame")) { - //Graphic Frame + // Graphic Frame m_objectType = GraphicFrame; loadXmlObjectGraphicFrame(reader); } else if (reader.name() == QLatin1String("cxnSp")) { - //Connection Shape + // Connection Shape m_objectType = ConnectionShape; loadXmlObjectConnectionShape(reader); } else if (reader.name() == QLatin1String("pic")) { - //Picture + // Picture m_objectType = Picture; loadXmlObjectPicture(reader); } @@ -194,19 +194,21 @@ void DrawingAnchor::loadXmlObjectGraphicFrame(QXmlStreamReader &reader) if (reader.name() == QLatin1String("chart")) { QString rId = reader.attributes().value(QLatin1String("r:id")).toString(); QString name = m_drawing->relationships()->getRelationshipById(rId).target; - QString path = QDir::cleanPath(splitPath(m_drawing->filePath())[0] + QLatin1String("/") + name); + QString path = QDir::cleanPath(splitPath(m_drawing->filePath())[0] + + QLatin1String("/") + name); bool exist = false; - QList > cfs = m_drawing->workbook->chartFiles(); - for (int i=0; i> cfs = m_drawing->workbook->chartFiles(); + for (int i = 0; i < cfs.size(); ++i) { if (cfs[i]->filePath() == path) { - //already exist + // already exist exist = true; m_chartFile = cfs[i]; } } if (!exist) { - m_chartFile = QSharedPointer (new Chart(m_drawing->sheet, Chart::F_LoadFromExists)); + m_chartFile = + QSharedPointer(new Chart(m_drawing->sheet, Chart::F_LoadFromExists)); m_chartFile->setFilePath(path); m_drawing->workbook->addChartFile(m_chartFile); } @@ -235,19 +237,20 @@ void DrawingAnchor::loadXmlObjectPicture(QXmlStreamReader &reader) if (reader.name() == QLatin1String("blip")) { QString rId = reader.attributes().value(QLatin1String("r:embed")).toString(); QString name = m_drawing->relationships()->getRelationshipById(rId).target; - QString path = QDir::cleanPath(splitPath(m_drawing->filePath())[0] + QLatin1String("/") + name); + QString path = QDir::cleanPath(splitPath(m_drawing->filePath())[0] + + QLatin1String("/") + name); bool exist = false; - QList > mfs = m_drawing->workbook->mediaFiles(); - for (int i=0; i> mfs = m_drawing->workbook->mediaFiles(); + for (int i = 0; i < mfs.size(); ++i) { if (mfs[i]->fileName() == path) { - //already exist + // already exist exist = true; m_pictureFile = mfs[i]; } } if (!exist) { - m_pictureFile = QSharedPointer (new MediaFile(path)); + m_pictureFile = QSharedPointer(new MediaFile(path)); m_drawing->workbook->addMediaFile(m_pictureFile, true); } } @@ -277,12 +280,13 @@ void DrawingAnchor::saveXmlExt(QXmlStreamWriter &writer, const QSize &ext) const writer.writeStartElement(QStringLiteral("xdr:ext")); writer.writeAttribute(QStringLiteral("cx"), QString::number(ext.width())); writer.writeAttribute(QStringLiteral("cy"), QString::number(ext.height())); - writer.writeEndElement(); //xdr:ext + writer.writeEndElement(); // xdr:ext } -void DrawingAnchor::saveXmlMarker(QXmlStreamWriter &writer, const XlsxMarker &marker, const QString &node) const +void DrawingAnchor::saveXmlMarker(QXmlStreamWriter &writer, const XlsxMarker &marker, + const QString &node) const { - writer.writeStartElement(node); //xdr:from or xdr:to + writer.writeStartElement(node); // xdr:from or xdr:to writer.writeTextElement(QStringLiteral("xdr:col"), QString::number(marker.col())); writer.writeTextElement(QStringLiteral("xdr:colOff"), QString::number(marker.colOff())); writer.writeTextElement(QStringLiteral("xdr:row"), QString::number(marker.row())); @@ -317,28 +321,34 @@ void DrawingAnchor::saveXmlObjectGraphicFrame(QXmlStreamWriter &writer) const writer.writeStartElement(QStringLiteral("xdr:nvGraphicFramePr")); writer.writeEmptyElement(QStringLiteral("xdr:cNvPr")); writer.writeAttribute(QStringLiteral("id"), QString::number(m_id)); - writer.writeAttribute(QStringLiteral("name"),QStringLiteral("Chart %1").arg(m_id)); + writer.writeAttribute(QStringLiteral("name"), QStringLiteral("Chart %1").arg(m_id)); writer.writeEmptyElement(QStringLiteral("xdr:cNvGraphicFramePr")); - writer.writeEndElement();//xdr:nvGraphicFramePr + writer.writeEndElement(); // xdr:nvGraphicFramePr writer.writeStartElement(QStringLiteral("xdr:xfrm")); - writer.writeEndElement(); //xdr:xfrm + writer.writeEndElement(); // xdr:xfrm writer.writeStartElement(QStringLiteral("a:graphic")); writer.writeStartElement(QStringLiteral("a:graphicData")); - writer.writeAttribute(QStringLiteral("uri"), QStringLiteral("http://schemas.openxmlformats.org/drawingml/2006/chart")); + writer.writeAttribute(QStringLiteral("uri"), + QStringLiteral("http://schemas.openxmlformats.org/drawingml/2006/chart")); int idx = m_drawing->workbook->chartFiles().indexOf(m_chartFile); - m_drawing->relationships()->addDocumentRelationship(QStringLiteral("/chart"), QStringLiteral("../charts/chart%1.xml").arg(idx+1)); + m_drawing->relationships()->addDocumentRelationship( + QStringLiteral("/chart"), QStringLiteral("../charts/chart%1.xml").arg(idx + 1)); writer.writeEmptyElement(QStringLiteral("c:chart")); - writer.writeAttribute(QStringLiteral("xmlns:c"), QStringLiteral("http://schemas.openxmlformats.org/drawingml/2006/chart")); - writer.writeAttribute(QStringLiteral("xmlns:r"), QStringLiteral("http://schemas.openxmlformats.org/officeDocument/2006/relationships")); - writer.writeAttribute(QStringLiteral("r:id"), QStringLiteral("rId%1").arg(m_drawing->relationships()->count())); + writer.writeAttribute(QStringLiteral("xmlns:c"), + QStringLiteral("http://schemas.openxmlformats.org/drawingml/2006/chart")); + writer.writeAttribute( + QStringLiteral("xmlns:r"), + QStringLiteral("http://schemas.openxmlformats.org/officeDocument/2006/relationships")); + writer.writeAttribute(QStringLiteral("r:id"), + QStringLiteral("rId%1").arg(m_drawing->relationships()->count())); - writer.writeEndElement(); //a:graphicData - writer.writeEndElement(); //a:graphic - writer.writeEndElement(); //xdr:graphicFrame + writer.writeEndElement(); // a:graphicData + writer.writeEndElement(); // a:graphic + writer.writeEndElement(); // xdr:graphicFrame } void DrawingAnchor::saveXmlObjectGroupShape(QXmlStreamWriter &writer) const @@ -360,46 +370,46 @@ void DrawingAnchor::saveXmlObjectPicture(QXmlStreamWriter &writer) const writer.writeStartElement(QStringLiteral("xdr:cNvPicPr")); writer.writeEmptyElement(QStringLiteral("a:picLocks")); writer.writeAttribute(QStringLiteral("noChangeAspect"), QStringLiteral("1")); - writer.writeEndElement(); //xdr:cNvPicPr + writer.writeEndElement(); // xdr:cNvPicPr - writer.writeEndElement(); //xdr:nvPicPr + writer.writeEndElement(); // xdr:nvPicPr - m_drawing->relationships()->addDocumentRelationship(QStringLiteral("/image"), QStringLiteral("../media/image%1.%2") - .arg(m_pictureFile->index()+1) - .arg(m_pictureFile->suffix())); + m_drawing->relationships()->addDocumentRelationship(QStringLiteral("/image"), + QStringLiteral("../media/image%1.%2") + .arg(m_pictureFile->index() + 1) + .arg(m_pictureFile->suffix())); writer.writeStartElement(QStringLiteral("xdr:blipFill")); writer.writeEmptyElement(QStringLiteral("a:blip")); - writer.writeAttribute(QStringLiteral("xmlns:r"), QStringLiteral("http://schemas.openxmlformats.org/officeDocument/2006/relationships")); - writer.writeAttribute(QStringLiteral("r:embed"), QStringLiteral("rId%1").arg(m_drawing->relationships()->count())); + writer.writeAttribute( + QStringLiteral("xmlns:r"), + QStringLiteral("http://schemas.openxmlformats.org/officeDocument/2006/relationships")); + writer.writeAttribute(QStringLiteral("r:embed"), + QStringLiteral("rId%1").arg(m_drawing->relationships()->count())); writer.writeStartElement(QStringLiteral("a:stretch")); writer.writeEmptyElement(QStringLiteral("a:fillRect")); - writer.writeEndElement(); //a:stretch - writer.writeEndElement();//xdr:blipFill + writer.writeEndElement(); // a:stretch + writer.writeEndElement(); // xdr:blipFill writer.writeStartElement(QStringLiteral("xdr:spPr")); writer.writeStartElement(QStringLiteral("a:prstGeom")); writer.writeAttribute(QStringLiteral("prst"), QStringLiteral("rect")); writer.writeEmptyElement(QStringLiteral("a:avLst")); - writer.writeEndElement(); //a:prstGeom + writer.writeEndElement(); // a:prstGeom - writer.writeEndElement(); //xdr:spPr + writer.writeEndElement(); // xdr:spPr - writer.writeEndElement(); //xdr:pic + writer.writeEndElement(); // xdr:pic } -void DrawingAnchor::saveXmlObjectShape(QXmlStreamWriter &writer) const -{ - Q_UNUSED(writer) -} +void DrawingAnchor::saveXmlObjectShape(QXmlStreamWriter &writer) const { Q_UNUSED(writer) } -//absolute anchor +// absolute anchor DrawingAbsoluteAnchor::DrawingAbsoluteAnchor(Drawing *drawing, ObjectType objectType) - :DrawingAnchor(drawing, objectType) + : DrawingAnchor(drawing, objectType) { - } bool DrawingAbsoluteAnchor::loadFromXml(QXmlStreamReader &reader) @@ -433,15 +443,14 @@ void DrawingAbsoluteAnchor::saveToXml(QXmlStreamWriter &writer) const saveXmlObject(writer); writer.writeEmptyElement(QStringLiteral("xdr:clientData")); - writer.writeEndElement(); //xdr:absoluteAnchor + writer.writeEndElement(); // xdr:absoluteAnchor } -//one cell anchor +// one cell anchor DrawingOneCellAnchor::DrawingOneCellAnchor(Drawing *drawing, ObjectType objectType) - :DrawingAnchor(drawing, objectType) + : DrawingAnchor(drawing, objectType) { - } bool DrawingOneCellAnchor::loadFromXml(QXmlStreamReader &reader) @@ -475,7 +484,7 @@ void DrawingOneCellAnchor::saveToXml(QXmlStreamWriter &writer) const saveXmlObject(writer); writer.writeEmptyElement(QStringLiteral("xdr:clientData")); - writer.writeEndElement(); //xdr:oneCellAnchor + writer.writeEndElement(); // xdr:oneCellAnchor } /* @@ -486,9 +495,8 @@ void DrawingOneCellAnchor::saveToXml(QXmlStreamWriter &writer) const cells and its extents are in EMU units. */ DrawingTwoCellAnchor::DrawingTwoCellAnchor(Drawing *drawing, ObjectType objectType) - :DrawingAnchor(drawing, objectType) + : DrawingAnchor(drawing, objectType) { - } bool DrawingTwoCellAnchor::loadFromXml(QXmlStreamReader &reader) @@ -523,7 +531,7 @@ void DrawingTwoCellAnchor::saveToXml(QXmlStreamWriter &writer) const saveXmlObject(writer); writer.writeEmptyElement(QStringLiteral("xdr:clientData")); - writer.writeEndElement(); //xdr:twoCellAnchor + writer.writeEndElement(); // xdr:twoCellAnchor } } // namespace QXlsx diff --git a/src/xlsx/xlsxdrawinganchor_p.h b/src/xlsx/xlsxdrawinganchor_p.h index 2f38a91..5f14821 100644 --- a/src/xlsx/xlsxdrawinganchor_p.h +++ b/src/xlsx/xlsxdrawinganchor_p.h @@ -42,20 +42,20 @@ class Drawing; class MediaFile; class Chart; -//Helper class +// Helper class struct XlsxMarker { - XlsxMarker(){} + XlsxMarker() {} XlsxMarker(int row, int column, int rowOffset, int colOffset) - :cell(QPoint(row, column)), offset(rowOffset, colOffset) + : cell(QPoint(row, column)) + , offset(rowOffset, colOffset) { - } - int row() const {return cell.x();} - int col() const {return cell.y();} - int rowOff() const {return offset.width();} - int colOff() const {return offset.height();} + int row() const { return cell.x(); } + int col() const { return cell.y(); } + int rowOff() const { return offset.width(); } + int colOff() const { return offset.height(); } QPoint cell; QSize offset; @@ -64,14 +64,7 @@ struct XlsxMarker class DrawingAnchor { public: - enum ObjectType { - GraphicFrame, - Shape, - GroupShape, - ConnectionShape, - Picture, - Unknown - }; + enum ObjectType { GraphicFrame, Shape, GroupShape, ConnectionShape, Picture, Unknown }; DrawingAnchor(Drawing *drawing, ObjectType objectType); virtual ~DrawingAnchor(); @@ -94,7 +87,8 @@ protected: void saveXmlPos(QXmlStreamWriter &writer, const QPoint &pos) const; void saveXmlExt(QXmlStreamWriter &writer, const QSize &ext) const; - void saveXmlMarker(QXmlStreamWriter &writer, const XlsxMarker &marker, const QString &node) const; + void saveXmlMarker(QXmlStreamWriter &writer, const XlsxMarker &marker, + const QString &node) const; void saveXmlObject(QXmlStreamWriter &writer) const; void saveXmlObjectShape(QXmlStreamWriter &writer) const; void saveXmlObjectGroupShape(QXmlStreamWriter &writer) const; @@ -113,7 +107,7 @@ protected: class DrawingAbsoluteAnchor : public DrawingAnchor { public: - DrawingAbsoluteAnchor(Drawing *drawing, ObjectType objectType=Unknown); + DrawingAbsoluteAnchor(Drawing *drawing, ObjectType objectType = Unknown); QPoint pos; QSize ext; @@ -125,7 +119,7 @@ public: class DrawingOneCellAnchor : public DrawingAnchor { public: - DrawingOneCellAnchor(Drawing *drawing, ObjectType objectType=Unknown); + DrawingOneCellAnchor(Drawing *drawing, ObjectType objectType = Unknown); XlsxMarker from; QSize ext; @@ -137,7 +131,7 @@ public: class DrawingTwoCellAnchor : public DrawingAnchor { public: - DrawingTwoCellAnchor(Drawing *drawing, ObjectType objectType=Unknown); + DrawingTwoCellAnchor(Drawing *drawing, ObjectType objectType = Unknown); XlsxMarker from; XlsxMarker to; diff --git a/src/xlsx/xlsxformat.cpp b/src/xlsx/xlsxformat.cpp index 074184f..7cb7602 100755 --- a/src/xlsx/xlsxformat.cpp +++ b/src/xlsx/xlsxformat.cpp @@ -33,32 +33,52 @@ QT_BEGIN_NAMESPACE_XLSX FormatPrivate::FormatPrivate() : dirty(true) - , font_dirty(true), font_index_valid(false), font_index(0) - , fill_dirty(true), fill_index_valid(false), fill_index(0) - , border_dirty(true), border_index_valid(false), border_index(0) - , xf_index(-1), xf_indexValid(false) - , is_dxf_fomat(false), dxf_index(-1), dxf_indexValid(false) + , font_dirty(true) + , font_index_valid(false) + , font_index(0) + , fill_dirty(true) + , fill_index_valid(false) + , fill_index(0) + , border_dirty(true) + , border_index_valid(false) + , border_index(0) + , xf_index(-1) + , xf_indexValid(false) + , is_dxf_fomat(false) + , dxf_index(-1) + , dxf_indexValid(false) , theme(0) { } FormatPrivate::FormatPrivate(const FormatPrivate &other) : QSharedData(other) - , dirty(other.dirty), formatKey(other.formatKey) - , font_dirty(other.font_dirty), font_index_valid(other.font_index_valid), font_key(other.font_key), font_index(other.font_index) - , fill_dirty(other.fill_dirty), fill_index_valid(other.fill_index_valid), fill_key(other.fill_key), fill_index(other.fill_index) - , border_dirty(other.border_dirty), border_index_valid(other.border_index_valid), border_key(other.border_key), border_index(other.border_index) - , xf_index(other.xf_index), xf_indexValid(other.xf_indexValid) - , is_dxf_fomat(other.is_dxf_fomat), dxf_index(other.dxf_index), dxf_indexValid(other.dxf_indexValid) + , dirty(other.dirty) + , formatKey(other.formatKey) + , font_dirty(other.font_dirty) + , font_index_valid(other.font_index_valid) + , font_key(other.font_key) + , font_index(other.font_index) + , fill_dirty(other.fill_dirty) + , fill_index_valid(other.fill_index_valid) + , fill_key(other.fill_key) + , fill_index(other.fill_index) + , border_dirty(other.border_dirty) + , border_index_valid(other.border_index_valid) + , border_key(other.border_key) + , border_index(other.border_index) + , xf_index(other.xf_index) + , xf_indexValid(other.xf_indexValid) + , is_dxf_fomat(other.is_dxf_fomat) + , dxf_index(other.dxf_index) + , dxf_indexValid(other.dxf_indexValid) , theme(other.theme) , properties(other.properties) { - } FormatPrivate::~FormatPrivate() { - } /*! @@ -77,7 +97,6 @@ FormatPrivate::~FormatPrivate() * \value FontScriptSub sub script */ - /*! * \enum Format::FontUnderline * @@ -136,7 +155,7 @@ FormatPrivate::~FormatPrivate() * \value BorderDashDotDot * \value BorderMediumDashDotDot * \value BorderSlantDashDot -*/ + */ /*! * \enum Format::DiagonalBorderType @@ -180,23 +199,22 @@ FormatPrivate::~FormatPrivate() */ Format::Format() { - //The d pointer is initialized with a null pointer + // The d pointer is initialized with a null pointer } /*! Creates a new format with the same attributes as the \a other format. */ Format::Format(const Format &other) - :d(other.d) + : d(other.d) { - } /*! Assigns the \a other format to this format, and returns a reference to this format. */ -Format &Format::operator =(const Format &other) +Format &Format::operator=(const Format &other) { d = other.d; return *this; @@ -247,7 +265,7 @@ void Format::setNumberFormat(const QString &format) if (format.isEmpty()) return; setProperty(FormatPrivate::P_NumFmt_FormatCode, format); - clearProperty(FormatPrivate::P_NumFmt_Id); //numFmt id must be re-generated. + clearProperty(FormatPrivate::P_NumFmt_Id); // numFmt id must be re-generated. } /*! @@ -256,18 +274,18 @@ void Format::setNumberFormat(const QString &format) bool Format::isDateTimeFormat() const { if (hasProperty(FormatPrivate::P_NumFmt_FormatCode)) { - //Custom numFmt, so - //Gauss from the number string + // Custom numFmt, so + // Gauss from the number string return NumFormatParser::isDateTime(numberFormat()); - } else if (hasProperty(FormatPrivate::P_NumFmt_Id)){ - //Non-custom numFmt + } else if (hasProperty(FormatPrivate::P_NumFmt_Id)) { + // Non-custom numFmt int idx = numberFormatIndex(); - //Is built-in date time number id? + // Is built-in date time number id? if ((idx >= 14 && idx <= 22) || (idx >= 45 && idx <= 47)) return true; - if ((idx >= 27 && idx <= 36) || (idx >= 50 && idx <= 58)) //Used in CHS\CHT\JPN\KOR + if ((idx >= 27 && idx <= 36) || (idx >= 50 && idx <= 58)) // Used in CHS\CHT\JPN\KOR return true; } @@ -304,7 +322,7 @@ bool Format::hasNumFmtData() const return false; if (hasProperty(FormatPrivate::P_NumFmt_Id) - || hasProperty(FormatPrivate::P_NumFmt_FormatCode)) { + || hasProperty(FormatPrivate::P_NumFmt_FormatCode)) { return true; } return false; @@ -461,15 +479,15 @@ void Format::setFontName(const QString &name) */ QFont Format::font() const { - QFont font; - font.setFamily(fontName()); - if (fontSize() > 0) - font.setPointSize(fontSize()); - font.setBold(fontBold()); - font.setItalic(fontItalic()); - font.setUnderline(fontUnderline()!=FontUnderlineNone); - font.setStrikeOut(fontStrikeOut()); - return font; + QFont font; + font.setFamily(fontName()); + if (fontSize() > 0) + font.setPointSize(fontSize()); + font.setBold(fontBold()); + font.setItalic(fontItalic()); + font.setUnderline(fontUnderline() != FontUnderlineNone); + font.setStrikeOut(fontStrikeOut()); + return font; } /*! @@ -529,13 +547,13 @@ QByteArray Format::fontKey() const if (d->font_dirty) { QByteArray key; QDataStream stream(&key, QIODevice::WriteOnly); - for (int i=FormatPrivate::P_Font_STARTID; iproperties.contains(i)) stream << i << d->properties[i]; }; - const_cast(this)->d->font_key = key; - const_cast(this)->d->font_dirty = false; + const_cast(this)->d->font_key = key; + const_cast(this)->d->font_dirty = false; } return d->font_key; @@ -550,7 +568,7 @@ bool Format::hasFontData() const if (!d) return false; - for (int i=FormatPrivate::P_Font_STARTID; i(intProperty(FormatPrivate::P_Alignment_AlignH, AlignHGeneral)); + return static_cast( + intProperty(FormatPrivate::P_Alignment_AlignH, AlignHGeneral)); } /*! @@ -571,12 +590,13 @@ Format::HorizontalAlignment Format::horizontalAlignment() const void Format::setHorizontalAlignment(HorizontalAlignment align) { if (hasProperty(FormatPrivate::P_Alignment_Indent) - &&(align != AlignHGeneral && align != AlignLeft && align != AlignRight && align != AlignHDistributed)) { + && (align != AlignHGeneral && align != AlignLeft && align != AlignRight + && align != AlignHDistributed)) { clearProperty(FormatPrivate::P_Alignment_Indent); } if (hasProperty(FormatPrivate::P_Alignment_ShinkToFit) - && (align == AlignHFill || align == AlignHJustify || align == AlignHDistributed)) { + && (align == AlignHFill || align == AlignHJustify || align == AlignHDistributed)) { clearProperty(FormatPrivate::P_Alignment_ShinkToFit); } @@ -588,7 +608,8 @@ void Format::setHorizontalAlignment(HorizontalAlignment align) */ Format::VerticalAlignment Format::verticalAlignment() const { - return static_cast(intProperty(FormatPrivate::P_Alignment_AlignV, AlignBottom)); + return static_cast( + intProperty(FormatPrivate::P_Alignment_AlignV, AlignBottom)); } /*! @@ -650,7 +671,7 @@ void Format::setIndent(int indent) if (indent && hasProperty(FormatPrivate::P_Alignment_AlignH)) { HorizontalAlignment hl = horizontalAlignment(); - if (hl != AlignHGeneral && hl != AlignLeft && hl!= AlignRight && hl!= AlignHJustify) { + if (hl != AlignHGeneral && hl != AlignLeft && hl != AlignRight && hl != AlignHJustify) { setHorizontalAlignment(AlignLeft); } } @@ -691,7 +712,7 @@ bool Format::hasAlignmentData() const if (!d) return false; - for (int i=FormatPrivate::P_Alignment_STARTID; iborder_dirty) { QByteArray key; QDataStream stream(&key, QIODevice::WriteOnly); - for (int i=FormatPrivate::P_Border_STARTID; iproperties.contains(i)) stream << i << d->properties[i]; }; - const_cast(this)->d->border_key = key; - const_cast(this)->d->border_dirty = false; + const_cast(this)->d->border_key = key; + const_cast(this)->d->border_dirty = false; } return d->border_key; @@ -958,7 +979,7 @@ bool Format::hasBorderData() const if (!d) return false; - for (int i=FormatPrivate::P_Border_STARTID; ifill_dirty) { QByteArray key; QDataStream stream(&key, QIODevice::WriteOnly); - for (int i=FormatPrivate::P_Fill_STARTID; iproperties.contains(i)) stream << i << d->properties[i]; }; - const_cast(this)->d->fill_key = key; - const_cast(this)->d->fill_dirty = false; + const_cast(this)->d->fill_key = key; + const_cast(this)->d->fill_dirty = false; } return d->fill_key; @@ -1078,7 +1099,7 @@ bool Format::hasFillData() const if (!d) return false; - for (int i=FormatPrivate::P_Fill_STARTID; i it(modifier.d->properties); - while(it.hasNext()) { + while (it.hasNext()) { it.next(); setProperty(it.key(), it.value()); } @@ -1188,7 +1208,7 @@ QByteArray Format::formatKey() const QMapIterator i(d->properties); while (i.hasNext()) { i.next(); - stream<formatKey = key; @@ -1267,7 +1287,7 @@ bool Format::dxfIndexValid() const /*! Returns ture if the \a format is equal to this format. */ -bool Format::operator ==(const Format &format) const +bool Format::operator==(const Format &format) const { return this->formatKey() == format.formatKey(); } @@ -1275,7 +1295,7 @@ bool Format::operator ==(const Format &format) const /*! Returns ture if the \a format is not equal to this format. */ -bool Format::operator !=(const Format &format) const +bool Format::operator!=(const Format &format) const { return this->formatKey() != format.formatKey(); } @@ -1298,7 +1318,8 @@ QVariant Format::property(int propertyId, const QVariant &defaultValue) const /*! * \internal */ -void Format::setProperty(int propertyId, const QVariant &value, const QVariant &clearValue, bool detach) +void Format::setProperty(int propertyId, const QVariant &value, const QVariant &clearValue, + bool detach) { if (!d) d = new FormatPrivate; @@ -1324,10 +1345,12 @@ void Format::setProperty(int propertyId, const QVariant &value, const QVariant & if (propertyId >= FormatPrivate::P_Font_STARTID && propertyId < FormatPrivate::P_Font_ENDID) { d->font_dirty = true; d->font_index_valid = false; - } else if (propertyId >= FormatPrivate::P_Border_STARTID && propertyId < FormatPrivate::P_Border_ENDID) { + } else if (propertyId >= FormatPrivate::P_Border_STARTID + && propertyId < FormatPrivate::P_Border_ENDID) { d->border_dirty = true; d->border_index_valid = false; - } else if (propertyId >= FormatPrivate::P_Fill_STARTID && propertyId < FormatPrivate::P_Fill_ENDID) { + } else if (propertyId >= FormatPrivate::P_Fill_STARTID + && propertyId < FormatPrivate::P_Fill_ENDID) { d->fill_dirty = true; d->fill_index_valid = false; } diff --git a/src/xlsx/xlsxformat.h b/src/xlsx/xlsxformat.h index 0923d0e..3beeef1 100755 --- a/src/xlsx/xlsxformat.h +++ b/src/xlsx/xlsxformat.h @@ -47,15 +47,9 @@ class FormatPrivate; class Q_XLSX_EXPORT Format { public: - enum FontScript - { - FontScriptNormal, - FontScriptSuper, - FontScriptSub - }; + enum FontScript { FontScriptNormal, FontScriptSuper, FontScriptSub }; - enum FontUnderline - { + enum FontUnderline { FontUnderlineNone, FontUnderlineSingle, FontUnderlineDouble, @@ -63,8 +57,7 @@ public: FontUnderlineDoubleAccounting }; - enum HorizontalAlignment - { + enum HorizontalAlignment { AlignHGeneral, AlignLeft, AlignHCenter, @@ -75,8 +68,7 @@ public: AlignHDistributed }; - enum VerticalAlignment - { + enum VerticalAlignment { AlignTop, AlignVCenter, AlignBottom, @@ -84,8 +76,7 @@ public: AlignVDistributed }; - enum BorderStyle - { + enum BorderStyle { BorderNone, BorderThin, BorderMedium, @@ -102,16 +93,14 @@ public: BorderSlantDashDot }; - enum DiagonalBorderType - { + enum DiagonalBorderType { DiagonalBorderNone, DiagonalBorderDown, DiagonalBorderUp, DiagnoalBorderBoth }; - enum FillPattern - { + enum FillPattern { PatternNone, PatternSolid, PatternMediumGray, @@ -220,16 +209,17 @@ public: bool isValid() const; bool isEmpty() const; - bool operator == (const Format &format) const; - bool operator != (const Format &format) const; + bool operator==(const Format &format) const; + bool operator!=(const Format &format) const; - QVariant property(int propertyId, const QVariant &defaultValue=QVariant()) const; - void setProperty(int propertyId, const QVariant &value, const QVariant &clearValue=QVariant(), bool detach=true); + QVariant property(int propertyId, const QVariant &defaultValue = QVariant()) const; + void setProperty(int propertyId, const QVariant &value, const QVariant &clearValue = QVariant(), + bool detach = true); void clearProperty(int propertyId); bool hasProperty(int propertyId) const; - bool boolProperty(int propertyId, bool defaultValue=false) const; - int intProperty(int propertyId, int defaultValue=0) const; + bool boolProperty(int propertyId, bool defaultValue = false) const; + int intProperty(int propertyId, int defaultValue = 0) const; double doubleProperty(int propertyId, double defaultValue = 0.0) const; QString stringProperty(int propertyId, const QString &defaultValue = QString()) const; QColor colorProperty(int propertyId, const QColor &defaultValue = QColor()) const; @@ -263,6 +253,7 @@ public: void setFillIndex(int index); void setXfIndex(int index); void setDxfIndex(int index); + private: friend class Styles; friend class ::FormatTest; diff --git a/src/xlsx/xlsxformat_p.h b/src/xlsx/xlsxformat_p.h index 85752f5..2a9afec 100644 --- a/src/xlsx/xlsxformat_p.h +++ b/src/xlsx/xlsxformat_p.h @@ -46,8 +46,7 @@ namespace QXlsx { class FormatPrivate : public QSharedData { public: - enum FormatType - { + enum FormatType { FT_Invalid = 0, FT_NumFmt = 0x01, FT_Font = 0x02, @@ -60,11 +59,11 @@ public: enum Property { P_STARTID, - //numFmt + // numFmt P_NumFmt_Id, P_NumFmt_FormatCode, - //font + // font P_Font_STARTID, P_Font_Size = P_Font_STARTID, P_Font_Italic, @@ -83,7 +82,7 @@ public: P_Font_Extend, P_Font_ENDID, - //border + // border P_Border_STARTID, P_Border_LeftStyle = P_Border_STARTID, P_Border_RightStyle, @@ -98,14 +97,14 @@ public: P_Border_DiagonalType, P_Border_ENDID, - //fill + // fill P_Fill_STARTID, P_Fill_Pattern = P_Fill_STARTID, P_Fill_BgColor, P_Fill_FgColor, P_Fill_ENDID, - //alignment + // alignment P_Alignment_STARTID, P_Alignment_AlignH = P_Alignment_STARTID, P_Alignment_AlignV, @@ -115,7 +114,7 @@ public: P_Alignment_ShinkToFit, P_Alignment_ENDID, - //protection + // protection P_Protection_Locked, P_Protection_Hidden, @@ -126,7 +125,7 @@ public: FormatPrivate(const FormatPrivate &other); ~FormatPrivate(); - bool dirty; //The key re-generation is need. + bool dirty; // The key re-generation is need. QByteArray formatKey; bool font_dirty; @@ -155,7 +154,6 @@ public: QMap properties; }; - } #endif // XLSXFORMAT_P_H diff --git a/src/xlsx/xlsxglobal.h b/src/xlsx/xlsxglobal.h index 1e5f4a6..24d6b60 100644 --- a/src/xlsx/xlsxglobal.h +++ b/src/xlsx/xlsxglobal.h @@ -31,19 +31,19 @@ #define QTXLSX_USE_NAMESPACE using namespace QXlsx; #if !defined(QT_STATIC) && !defined(XLSX_NO_LIB) -# if defined(QT_BUILD_XLSX_LIB) -# define Q_XLSX_EXPORT Q_DECL_EXPORT -# else -# define Q_XLSX_EXPORT Q_DECL_IMPORT -# endif +#if defined(QT_BUILD_XLSX_LIB) +#define Q_XLSX_EXPORT Q_DECL_EXPORT #else -# define Q_XLSX_EXPORT +#define Q_XLSX_EXPORT Q_DECL_IMPORT +#endif +#else +#define Q_XLSX_EXPORT #endif #ifdef XLSX_TEST -# define XLSX_AUTOTEST_EXPORT Q_XLSX_EXPORT +#define XLSX_AUTOTEST_EXPORT Q_XLSX_EXPORT #else -# define XLSX_AUTOTEST_EXPORT +#define XLSX_AUTOTEST_EXPORT #endif #endif // XLSXGLOBAL_H diff --git a/src/xlsx/xlsxmediafile.cpp b/src/xlsx/xlsxmediafile.cpp index 39fbc03..a61a28a 100644 --- a/src/xlsx/xlsxmediafile.cpp +++ b/src/xlsx/xlsxmediafile.cpp @@ -29,16 +29,20 @@ namespace QXlsx { MediaFile::MediaFile(const QByteArray &bytes, const QString &suffix, const QString &mimeType) - : m_contents(bytes), m_suffix(suffix), m_mimeType(mimeType) - , m_index(0), m_indexValid(false) + : m_contents(bytes) + , m_suffix(suffix) + , m_mimeType(mimeType) + , m_index(0) + , m_indexValid(false) { m_hashKey = QCryptographicHash::hash(m_contents, QCryptographicHash::Md5); } MediaFile::MediaFile(const QString &fileName) - :m_fileName(fileName), m_index(0), m_indexValid(false) + : m_fileName(fileName) + , m_index(0) + , m_indexValid(false) { - } void MediaFile::set(const QByteArray &bytes, const QString &suffix, const QString &mimeType) diff --git a/src/xlsx/xlsxmediafile_p.h b/src/xlsx/xlsxmediafile_p.h index f38dcf2..5d2c81f 100644 --- a/src/xlsx/xlsxmediafile_p.h +++ b/src/xlsx/xlsxmediafile_p.h @@ -26,7 +26,6 @@ #ifndef QXLSX_XLSXMEDIAFILE_H #define QXLSX_XLSXMEDIAFILE_H - // // W A R N I N G // ------------- @@ -49,9 +48,9 @@ class MediaFile { public: MediaFile(const QString &fileName); - MediaFile(const QByteArray &bytes, const QString &suffix, const QString &mimeType=QString()); + MediaFile(const QByteArray &bytes, const QString &suffix, const QString &mimeType = QString()); - void set(const QByteArray &bytes, const QString &suffix, const QString &mimeType=QString()); + void set(const QByteArray &bytes, const QString &suffix, const QString &mimeType = QString()); QString suffix() const; QString mimeType() const; QByteArray contents() const; diff --git a/src/xlsx/xlsxnumformatparser.cpp b/src/xlsx/xlsxnumformatparser.cpp index 6e2a686..ca4c322 100644 --- a/src/xlsx/xlsxnumformatparser.cpp +++ b/src/xlsx/xlsxnumformatparser.cpp @@ -36,11 +36,11 @@ bool NumFormatParser::isDateTime(const QString &formatCode) switch (c.unicode()) { case '[': // [h], [m], [s] are valid format for time - if (i < formatCode.length()-2 && formatCode[i+2] == QLatin1Char(']')) { - const QChar cc = formatCode[i+1].toLower(); + if (i < formatCode.length() - 2 && formatCode[i + 2] == QLatin1Char(']')) { + const QChar cc = formatCode[i + 1].toLower(); if (cc == QLatin1Char('h') || cc == QLatin1Char('m') || cc == QLatin1Char('s')) return true; - i+=2; + i += 2; break; } else { // condition or color: don't care, ignore @@ -51,7 +51,7 @@ bool NumFormatParser::isDateTime(const QString &formatCode) // quoted plain text block: don't care, ignore case '"': - while (i < formatCode.length()-1 && formatCode[++i] != QLatin1Char('"')) + while (i < formatCode.length() - 1 && formatCode[++i] != QLatin1Char('"')) ; break; diff --git a/src/xlsx/xlsxrelationships.cpp b/src/xlsx/xlsxrelationships.cpp index 2616182..1de0eb2 100755 --- a/src/xlsx/xlsxrelationships.cpp +++ b/src/xlsx/xlsxrelationships.cpp @@ -31,10 +31,14 @@ namespace QXlsx { -const QString schema_doc = QStringLiteral("http://schemas.openxmlformats.org/officeDocument/2006/relationships"); -const QString schema_msPackage = QStringLiteral("http://schemas.microsoft.com/office/2006/relationships"); -const QString schema_package = QStringLiteral("http://schemas.openxmlformats.org/package/2006/relationships"); -//const QString schema_worksheet = QStringLiteral("http://schemas.openxmlformats.org/officeDocument/2006/relationships"); +const QString schema_doc = + QStringLiteral("http://schemas.openxmlformats.org/officeDocument/2006/relationships"); +const QString schema_msPackage = + QStringLiteral("http://schemas.microsoft.com/office/2006/relationships"); +const QString schema_package = + QStringLiteral("http://schemas.openxmlformats.org/package/2006/relationships"); +// const QString schema_worksheet = +// QStringLiteral("http://schemas.openxmlformats.org/officeDocument/2006/relationships"); Relationships::Relationships() { } @@ -74,7 +78,8 @@ QList Relationships::worksheetRelationships(const QString &rel return relationships(schema_doc + relativeType); } -void Relationships::addWorksheetRelationship(const QString &relativeType, const QString &target, const QString &targetMode) +void Relationships::addWorksheetRelationship(const QString &relativeType, const QString &target, + const QString &targetMode) { addRelationship(schema_doc + relativeType, target, targetMode); } @@ -89,10 +94,11 @@ QList Relationships::relationships(const QString &type) const return res; } -void Relationships::addRelationship(const QString &type, const QString &target, const QString &targetMode) +void Relationships::addRelationship(const QString &type, const QString &target, + const QString &targetMode) { XlsxRelationship relation; - relation.id = QStringLiteral("rId%1").arg(m_relationships.size()+1); + relation.id = QStringLiteral("rId%1").arg(m_relationships.size() + 1); relation.type = type; relation.target = target; relation.targetMode = targetMode; @@ -106,7 +112,9 @@ void Relationships::saveToXmlFile(QIODevice *device) const writer.writeStartDocument(QStringLiteral("1.0"), true); writer.writeStartElement(QStringLiteral("Relationships")); - writer.writeAttribute(QStringLiteral("xmlns"), QStringLiteral("http://schemas.openxmlformats.org/package/2006/relationships")); + writer.writeAttribute( + QStringLiteral("xmlns"), + QStringLiteral("http://schemas.openxmlformats.org/package/2006/relationships")); foreach (XlsxRelationship relation, m_relationships) { writer.writeStartElement(QStringLiteral("Relationship")); writer.writeAttribute(QStringLiteral("Id"), relation.id); @@ -116,7 +124,7 @@ void Relationships::saveToXmlFile(QIODevice *device) const writer.writeAttribute(QStringLiteral("TargetMode"), relation.targetMode); writer.writeEndElement(); } - writer.writeEndElement();//Relationships + writer.writeEndElement(); // Relationships writer.writeEndDocument(); } @@ -135,20 +143,20 @@ bool Relationships::loadFromXmlFile(QIODevice *device) clear(); QXmlStreamReader reader(device); while (!reader.atEnd()) { - QXmlStreamReader::TokenType token = reader.readNext(); - if (token == QXmlStreamReader::StartElement) { - if (reader.name() == QStringLiteral("Relationship")) { - QXmlStreamAttributes attributes = reader.attributes(); - XlsxRelationship relationship; - relationship.id = attributes.value(QLatin1String("Id")).toString(); - relationship.type = attributes.value(QLatin1String("Type")).toString(); - relationship.target = attributes.value(QLatin1String("Target")).toString(); - relationship.targetMode = attributes.value(QLatin1String("TargetMode")).toString(); - m_relationships.append(relationship); - } - } + QXmlStreamReader::TokenType token = reader.readNext(); + if (token == QXmlStreamReader::StartElement) { + if (reader.name() == QStringLiteral("Relationship")) { + QXmlStreamAttributes attributes = reader.attributes(); + XlsxRelationship relationship; + relationship.id = attributes.value(QLatin1String("Id")).toString(); + relationship.type = attributes.value(QLatin1String("Type")).toString(); + relationship.target = attributes.value(QLatin1String("Target")).toString(); + relationship.targetMode = attributes.value(QLatin1String("TargetMode")).toString(); + m_relationships.append(relationship); + } + } - if (reader.hasError()) + if (reader.hasError()) return false; } return true; @@ -186,4 +194,4 @@ bool Relationships::isEmpty() const return m_relationships.isEmpty(); } -} //namespace +} // namespace diff --git a/src/xlsx/xlsxrelationships_p.h b/src/xlsx/xlsxrelationships_p.h index c1afee5..371649a 100755 --- a/src/xlsx/xlsxrelationships_p.h +++ b/src/xlsx/xlsxrelationships_p.h @@ -64,7 +64,8 @@ public: void addDocumentRelationship(const QString &relativeType, const QString &target); void addPackageRelationship(const QString &relativeType, const QString &target); void addMsPackageRelationship(const QString &relativeType, const QString &target); - void addWorksheetRelationship(const QString &relativeType, const QString &target, const QString &targetMode=QString()); + void addWorksheetRelationship(const QString &relativeType, const QString &target, + const QString &targetMode = QString()); void saveToXmlFile(QIODevice *device) const; QByteArray saveToXmlData() const; @@ -78,10 +79,10 @@ public: private: QList relationships(const QString &type) const; - void addRelationship(const QString &type, const QString &target, const QString &targetMode=QString()); + void addRelationship(const QString &type, const QString &target, + const QString &targetMode = QString()); QList m_relationships; }; - } #endif // XLSXRELATIONSHIPS_H diff --git a/src/xlsx/xlsxrichstring.cpp b/src/xlsx/xlsxrichstring.cpp index 4d02594..342ce2c 100644 --- a/src/xlsx/xlsxrichstring.cpp +++ b/src/xlsx/xlsxrichstring.cpp @@ -32,22 +32,21 @@ QT_BEGIN_NAMESPACE_XLSX RichStringPrivate::RichStringPrivate() - :_dirty(true) + : _dirty(true) { - } RichStringPrivate::RichStringPrivate(const RichStringPrivate &other) - :QSharedData(other), fragmentTexts(other.fragmentTexts) - ,fragmentFormats(other.fragmentFormats) - , _idKey(other.idKey()), _dirty(other._dirty) + : QSharedData(other) + , fragmentTexts(other.fragmentTexts) + , fragmentFormats(other.fragmentFormats) + , _idKey(other.idKey()) + , _dirty(other._dirty) { - } RichStringPrivate::~RichStringPrivate() { - } /*! @@ -60,7 +59,7 @@ RichStringPrivate::~RichStringPrivate() Constructs a null string. */ RichString::RichString() - :d(new RichStringPrivate) + : d(new RichStringPrivate) { } @@ -68,7 +67,7 @@ RichString::RichString() Constructs a plain string with the given \a text. */ RichString::RichString(const QString text) - :d(new RichStringPrivate) + : d(new RichStringPrivate) { addFragment(text, Format()); } @@ -77,9 +76,8 @@ RichString::RichString(const QString text) Constructs a copy of \a other. */ RichString::RichString(const RichString &other) - :d(other.d) + : d(other.d) { - } /*! @@ -87,13 +85,12 @@ RichString::RichString(const RichString &other) */ RichString::~RichString() { - } /*! Assigns \a other to this string and returns a reference to this string */ -RichString &RichString::operator =(const RichString &other) +RichString &RichString::operator=(const RichString &other) { this->d = other.d; return *this; @@ -112,7 +109,7 @@ RichString::operator QVariant() const */ bool RichString::isRichString() const { - if (fragmentCount() > 1) //Is this enough?? + if (fragmentCount() > 1) // Is this enough?? return true; return false; } @@ -232,9 +229,9 @@ QByteArray RichStringPrivate::idKey() const if (fragmentTexts.size() == 1) { bytes = fragmentTexts[0].toUtf8(); } else { - //Generate a hash value base on QByteArray ? + // Generate a hash value base on QByteArray ? bytes.append("@@QtXlsxRichString="); - for (int i=0; i= m_stringList.size()) { + if (idx < 0 || idx >= m_stringList.size()) { qDebug("SharedStrings: invlid index"); return; } @@ -113,7 +113,7 @@ void SharedStrings::removeSharedString(const RichString &string) item.count -= 1; if (item.count <= 0) { - for (int i=item.index+1; i m_stringTable; //for fast lookup + QHash m_stringTable; // for fast lookup QList m_stringList; int m_stringCount; }; - } #endif // XLSXSHAREDSTRINGS_H diff --git a/src/xlsx/xlsxsimpleooxmlfile.cpp b/src/xlsx/xlsxsimpleooxmlfile.cpp index 76855bb..a460321 100644 --- a/src/xlsx/xlsxsimpleooxmlfile.cpp +++ b/src/xlsx/xlsxsimpleooxmlfile.cpp @@ -27,7 +27,7 @@ namespace QXlsx { SimpleOOXmlFile::SimpleOOXmlFile(CreateFlag flag) - :AbstractOOXmlFile(flag) + : AbstractOOXmlFile(flag) { } @@ -52,5 +52,4 @@ bool SimpleOOXmlFile::loadFromXmlFile(QIODevice *device) xmlData = device->readAll(); return true; } - } diff --git a/src/xlsx/xlsxsimpleooxmlfile_p.h b/src/xlsx/xlsxsimpleooxmlfile_p.h index 3ee875a..00651fb 100644 --- a/src/xlsx/xlsxsimpleooxmlfile_p.h +++ b/src/xlsx/xlsxsimpleooxmlfile_p.h @@ -54,6 +54,5 @@ public: QByteArray xmlData; }; - } #endif // XLSXSIMPLEOOXMLFILE_H diff --git a/src/xlsx/xlsxstyles.cpp b/src/xlsx/xlsxstyles.cpp index 4a3cb3a..f4c0c25 100755 --- a/src/xlsx/xlsxstyles.cpp +++ b/src/xlsx/xlsxstyles.cpp @@ -42,12 +42,14 @@ namespace QXlsx { */ Styles::Styles(CreateFlag flag) - : AbstractOOXmlFile(flag), m_nextCustomNumFmtId(176), m_isIndexedColorsDefault(true) + : AbstractOOXmlFile(flag) + , m_nextCustomNumFmtId(176) + , m_isIndexedColorsDefault(true) , m_emptyFormatAdded(false) { - //!Fix me. Should the custom num fmt Id starts with 164 or 176 or others?? + //! Fix me. Should the custom num fmt Id starts with 164 or 176 or others?? - //!Fix me! Where should we put these register code? + //! Fix me! Where should we put these register code? if (QMetaType::type("XlsxColor") == QMetaType::UnknownType) { qRegisterMetaType("XlsxColor"); qRegisterMetaTypeStreamOperators("XlsxColor"); @@ -57,11 +59,11 @@ Styles::Styles(CreateFlag flag) } if (flag == F_NewFromScratch) { - //Add default Format + // Add default Format Format defaultFmt; addXfFormat(defaultFmt); - //Add another fill format + // Add another fill format Format fillFmt; fillFmt.setFillPattern(Format::PatternGray125); m_fillsList.append(fillFmt); @@ -75,7 +77,7 @@ Styles::~Styles() Format Styles::xfFormat(int idx) const { - if (idx <0 || idx >= m_xf_formatsList.size()) + if (idx < 0 || idx >= m_xf_formatsList.size()) return Format(); return m_xf_formatsList[idx]; @@ -83,7 +85,7 @@ Format Styles::xfFormat(int idx) const Format Styles::dxfFormat(int idx) const { - if (idx <0 || idx >= m_dxf_formatsList.size()) + if (idx < 0 || idx >= m_dxf_formatsList.size()) return Format(); return m_dxf_formatsList[idx]; @@ -95,7 +97,7 @@ void Styles::fixNumFmt(const Format &format) return; if (format.hasProperty(FormatPrivate::P_NumFmt_Id) - && !format.stringProperty(FormatPrivate::P_NumFmt_FormatCode).isEmpty()) { + && !format.stringProperty(FormatPrivate::P_NumFmt_FormatCode).isEmpty()) { return; } @@ -105,15 +107,17 @@ void Styles::fixNumFmt(const Format &format) m_builtinNumFmtsHash.insert(QStringLiteral("0.00"), 2); m_builtinNumFmtsHash.insert(QStringLiteral("#,##0"), 3); m_builtinNumFmtsHash.insert(QStringLiteral("#,##0.00"), 4); -// m_builtinNumFmtsHash.insert(QStringLiteral("($#,##0_);($#,##0)"), 5); -// m_builtinNumFmtsHash.insert(QStringLiteral("($#,##0_);[Red]($#,##0)"), 6); -// m_builtinNumFmtsHash.insert(QStringLiteral("($#,##0.00_);($#,##0.00)"), 7); -// m_builtinNumFmtsHash.insert(QStringLiteral("($#,##0.00_);[Red]($#,##0.00)"), 8); + // m_builtinNumFmtsHash.insert(QStringLiteral("($#,##0_);($#,##0)"), 5); + // m_builtinNumFmtsHash.insert(QStringLiteral("($#,##0_);[Red]($#,##0)"), 6); + // m_builtinNumFmtsHash.insert(QStringLiteral("($#,##0.00_);($#,##0.00)"), 7); + // m_builtinNumFmtsHash.insert(QStringLiteral("($#,##0.00_);[Red]($#,##0.00)"), + // 8); m_builtinNumFmtsHash.insert(QStringLiteral("0%"), 9); m_builtinNumFmtsHash.insert(QStringLiteral("0.00%"), 10); m_builtinNumFmtsHash.insert(QStringLiteral("0.00E+00"), 11); m_builtinNumFmtsHash.insert(QStringLiteral("# ?/?"), 12); - m_builtinNumFmtsHash.insert(QStringLiteral("# ?\?/??"), 13);// Note: "??/" is a c++ trigraph, so escape one "?" + m_builtinNumFmtsHash.insert(QStringLiteral("# ?\?/??"), + 13); // Note: "??/" is a c++ trigraph, so escape one "?" m_builtinNumFmtsHash.insert(QStringLiteral("m/d/yy"), 14); m_builtinNumFmtsHash.insert(QStringLiteral("d-mmm-yy"), 15); m_builtinNumFmtsHash.insert(QStringLiteral("d-mmm"), 16); @@ -128,10 +132,12 @@ void Styles::fixNumFmt(const Format &format) m_builtinNumFmtsHash.insert(QStringLiteral("(#,##0_);[Red](#,##0)"), 38); m_builtinNumFmtsHash.insert(QStringLiteral("(#,##0.00_);(#,##0.00)"), 39); m_builtinNumFmtsHash.insert(QStringLiteral("(#,##0.00_);[Red](#,##0.00)"), 40); -// m_builtinNumFmtsHash.insert(QStringLiteral("_(* #,##0_);_(* (#,##0);_(* \"-\"_);_(_)"), 41); -// m_builtinNumFmtsHash.insert(QStringLiteral("_($* #,##0_);_($* (#,##0);_($* \"-\"_);_(_)"), 42); -// m_builtinNumFmtsHash.insert(QStringLiteral("_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(_)"), 43); -// m_builtinNumFmtsHash.insert(QStringLiteral("_($* #,##0.00_);_($* (#,##0.00);_($* \"-\"??_);_(_)"), 44); + // m_builtinNumFmtsHash.insert(QStringLiteral("_(* #,##0_);_(* (#,##0);_(* + // \"-\"_);_(_)"), 41); m_builtinNumFmtsHash.insert(QStringLiteral("_($* + // #,##0_);_($* (#,##0);_($* \"-\"_);_(_)"), 42); + // m_builtinNumFmtsHash.insert(QStringLiteral("_(* #,##0.00_);_(* (#,##0.00);_(* + // \"-\"??_);_(_)"), 43); m_builtinNumFmtsHash.insert(QStringLiteral("_($* + // #,##0.00_);_($* (#,##0.00);_($* \"-\"??_);_(_)"), 44); m_builtinNumFmtsHash.insert(QStringLiteral("mm:ss"), 45); m_builtinNumFmtsHash.insert(QStringLiteral("[h]:mm:ss"), 46); m_builtinNumFmtsHash.insert(QStringLiteral("mm:ss.0"), 47); @@ -141,13 +147,14 @@ void Styles::fixNumFmt(const Format &format) const QString str = format.numberFormat(); if (!str.isEmpty()) { - //Assign proper number format index + // Assign proper number format index if (m_builtinNumFmtsHash.contains(str)) { const_cast(&format)->fixNumberFormat(m_builtinNumFmtsHash[str], str); } else if (m_customNumFmtsHash.contains(str)) { - const_cast(&format)->fixNumberFormat(m_customNumFmtsHash[str]->formatIndex, str); + const_cast(&format)->fixNumberFormat(m_customNumFmtsHash[str]->formatIndex, + str); } else { - //Assign a new fmt Id. + // Assign a new fmt Id. const_cast(&format)->fixNumberFormat(m_nextCustomNumFmtId, str); QSharedPointer fmt(new XlsxFormatNumberData); @@ -160,12 +167,13 @@ void Styles::fixNumFmt(const Format &format) } } else { int id = format.numberFormatIndex(); - //Assign proper format code, this is needed by dxf format + // Assign proper format code, this is needed by dxf format if (m_customNumFmtIdMap.contains(id)) { - const_cast(&format)->fixNumberFormat(id, m_customNumFmtIdMap[id]->formatString); + const_cast(&format)->fixNumberFormat(id, + m_customNumFmtIdMap[id]->formatString); } else { QHashIterator it(m_builtinNumFmtsHash); - bool find=false; + bool find = false; while (it.hasNext()) { it.next(); if (it.value() == id) { @@ -176,7 +184,7 @@ void Styles::fixNumFmt(const Format &format) } if (!find) { - //Wrong numFmt + // Wrong numFmt const_cast(&format)->fixNumberFormat(id, QStringLiteral("General")); } } @@ -193,62 +201,64 @@ void Styles::fixNumFmt(const Format &format) void Styles::addXfFormat(const Format &format, bool force) { if (format.isEmpty()) { - //Try do something for empty Format. + // Try do something for empty Format. if (m_emptyFormatAdded && !force) return; m_emptyFormatAdded = true; } - //numFmt + // numFmt if (format.hasNumFmtData() && !format.hasProperty(FormatPrivate::P_NumFmt_Id)) fixNumFmt(format); - //Font + // Font if (format.hasFontData() && !format.fontIndexValid()) { - //Assign proper font index, if has font data. + // Assign proper font index, if has font data. if (!m_fontsHash.contains(format.fontKey())) const_cast(&format)->setFontIndex(m_fontsList.size()); else const_cast(&format)->setFontIndex(m_fontsHash[format.fontKey()].fontIndex()); } if (!m_fontsHash.contains(format.fontKey())) { - //Still a valid font if the format has no fontData. (All font properties are default) + // Still a valid font if the format has no fontData. (All font properties are default) m_fontsList.append(format); m_fontsHash[format.fontKey()] = format; } - //Fill + // Fill if (format.hasFillData() && !format.fillIndexValid()) { - //Assign proper fill index, if has fill data. + // Assign proper fill index, if has fill data. if (!m_fillsHash.contains(format.fillKey())) const_cast(&format)->setFillIndex(m_fillsList.size()); else const_cast(&format)->setFillIndex(m_fillsHash[format.fillKey()].fillIndex()); } if (!m_fillsHash.contains(format.fillKey())) { - //Still a valid fill if the format has no fillData. (All fill properties are default) + // Still a valid fill if the format has no fillData. (All fill properties are default) m_fillsList.append(format); m_fillsHash[format.fillKey()] = format; } - //Border + // Border if (format.hasBorderData() && !format.borderIndexValid()) { - //Assign proper border index, if has border data. + // Assign proper border index, if has border data. if (!m_bordersHash.contains(format.borderKey())) const_cast(&format)->setBorderIndex(m_bordersList.size()); else - const_cast(&format)->setBorderIndex(m_bordersHash[format.borderKey()].borderIndex()); + const_cast(&format)->setBorderIndex( + m_bordersHash[format.borderKey()].borderIndex()); } if (!m_bordersHash.contains(format.borderKey())) { - //Still a valid border if the format has no borderData. (All border properties are default) + // Still a valid border if the format has no borderData. (All border properties are default) m_bordersList.append(format); m_bordersHash[format.borderKey()] = format; } - //Format + // Format if (!format.isEmpty() && !format.xfIndexValid()) { if (m_xf_formatsHash.contains(format.formatKey())) - const_cast(&format)->setXfIndex(m_xf_formatsHash[format.formatKey()].xfIndex()); + const_cast(&format)->setXfIndex( + m_xf_formatsHash[format.formatKey()].xfIndex()); else const_cast(&format)->setXfIndex(m_xf_formatsList.size()); } @@ -260,13 +270,14 @@ void Styles::addXfFormat(const Format &format, bool force) void Styles::addDxfFormat(const Format &format, bool force) { - //numFmt + // numFmt if (format.hasNumFmtData()) fixNumFmt(format); if (!format.isEmpty() && !format.dxfIndexValid()) { if (m_dxf_formatsHash.contains(format.formatKey())) - const_cast(&format)->setDxfIndex(m_dxf_formatsHash[format.formatKey()].dxfIndex()); + const_cast(&format)->setDxfIndex( + m_dxf_formatsHash[format.formatKey()].dxfIndex()); else const_cast(&format)->setDxfIndex(m_dxf_formatsList.size()); } @@ -282,7 +293,9 @@ void Styles::saveToXmlFile(QIODevice *device) const writer.writeStartDocument(QStringLiteral("1.0"), true); writer.writeStartElement(QStringLiteral("styleSheet")); - writer.writeAttribute(QStringLiteral("xmlns"), QStringLiteral("http://schemas.openxmlformats.org/spreadsheetml/2006/main")); + writer.writeAttribute( + QStringLiteral("xmlns"), + QStringLiteral("http://schemas.openxmlformats.org/spreadsheetml/2006/main")); writeNumFmts(writer); writeFonts(writer); @@ -296,8 +309,8 @@ void Styles::saveToXmlFile(QIODevice *device) const writer.writeAttribute(QStringLiteral("fontId"), QStringLiteral("0")); writer.writeAttribute(QStringLiteral("fillId"), QStringLiteral("0")); writer.writeAttribute(QStringLiteral("borderId"), QStringLiteral("0")); - writer.writeEndElement();//xf - writer.writeEndElement();//cellStyleXfs + writer.writeEndElement(); // xf + writer.writeEndElement(); // cellStyleXfs writeCellXfs(writer); @@ -307,8 +320,8 @@ void Styles::saveToXmlFile(QIODevice *device) const writer.writeAttribute(QStringLiteral("name"), QStringLiteral("Normal")); writer.writeAttribute(QStringLiteral("xfId"), QStringLiteral("0")); writer.writeAttribute(QStringLiteral("builtinId"), QStringLiteral("0")); - writer.writeEndElement();//cellStyle - writer.writeEndElement();//cellStyles + writer.writeEndElement(); // cellStyle + writer.writeEndElement(); // cellStyles writeDxfs(writer); @@ -316,11 +329,11 @@ void Styles::saveToXmlFile(QIODevice *device) const writer.writeAttribute(QStringLiteral("count"), QStringLiteral("0")); writer.writeAttribute(QStringLiteral("defaultTableStyle"), QStringLiteral("TableStyleMedium9")); writer.writeAttribute(QStringLiteral("defaultPivotStyle"), QStringLiteral("PivotStyleLight16")); - writer.writeEndElement();//tableStyles + writer.writeEndElement(); // tableStyles writeColors(writer); - writer.writeEndElement();//styleSheet + writer.writeEndElement(); // styleSheet writer.writeEndDocument(); } @@ -332,39 +345,39 @@ void Styles::writeNumFmts(QXmlStreamWriter &writer) const writer.writeStartElement(QStringLiteral("numFmts")); writer.writeAttribute(QStringLiteral("count"), QString::number(m_customNumFmtIdMap.count())); - QMapIterator > it(m_customNumFmtIdMap); + QMapIterator> it(m_customNumFmtIdMap); while (it.hasNext()) { it.next(); writer.writeEmptyElement(QStringLiteral("numFmt")); writer.writeAttribute(QStringLiteral("numFmtId"), QString::number(it.value()->formatIndex)); writer.writeAttribute(QStringLiteral("formatCode"), it.value()->formatString); } - writer.writeEndElement();//numFmts + writer.writeEndElement(); // numFmts } /* -*/ + */ void Styles::writeFonts(QXmlStreamWriter &writer) const { writer.writeStartElement(QStringLiteral("fonts")); writer.writeAttribute(QStringLiteral("count"), QString::number(m_fontsList.count())); - for (int i=0; i().saveToXml(writer, QStringLiteral("fgColor")); + fill.property(FormatPrivate::P_Fill_BgColor) + .value() + .saveToXml(writer, QStringLiteral("fgColor")); if (fill.hasProperty(FormatPrivate::P_Fill_FgColor)) - fill.property(FormatPrivate::P_Fill_FgColor).value().saveToXml(writer, QStringLiteral("bgColor")); + fill.property(FormatPrivate::P_Fill_FgColor) + .value() + .saveToXml(writer, QStringLiteral("bgColor")); } else { if (fill.hasProperty(FormatPrivate::P_Fill_FgColor)) - fill.property(FormatPrivate::P_Fill_FgColor).value().saveToXml(writer, QStringLiteral("fgColor")); + fill.property(FormatPrivate::P_Fill_FgColor) + .value() + .saveToXml(writer, QStringLiteral("fgColor")); if (fill.hasProperty(FormatPrivate::P_Fill_BgColor)) - fill.property(FormatPrivate::P_Fill_BgColor).value().saveToXml(writer, QStringLiteral("bgColor")); + fill.property(FormatPrivate::P_Fill_BgColor) + .value() + .saveToXml(writer, QStringLiteral("bgColor")); } - writer.writeEndElement();//patternFill - writer.writeEndElement();//fill + writer.writeEndElement(); // patternFill + writer.writeEndElement(); // fill } void Styles::writeBorders(QXmlStreamWriter &writer) const { writer.writeStartElement(QStringLiteral("borders")); writer.writeAttribute(QStringLiteral("count"), QString::number(m_bordersList.count())); - for (int i=0; i()); - writeSubBorder(writer, QStringLiteral("right"), border.rightBorderStyle(), border.property(FormatPrivate::P_Border_RightColor).value()); - writeSubBorder(writer, QStringLiteral("top"), border.topBorderStyle(), border.property(FormatPrivate::P_Border_TopColor).value()); - writeSubBorder(writer, QStringLiteral("bottom"), border.bottomBorderStyle(), border.property(FormatPrivate::P_Border_BottomColor).value()); + writeSubBorder(writer, QStringLiteral("left"), border.leftBorderStyle(), + border.property(FormatPrivate::P_Border_LeftColor).value()); + writeSubBorder(writer, QStringLiteral("right"), border.rightBorderStyle(), + border.property(FormatPrivate::P_Border_RightColor).value()); + writeSubBorder(writer, QStringLiteral("top"), border.topBorderStyle(), + border.property(FormatPrivate::P_Border_TopColor).value()); + writeSubBorder(writer, QStringLiteral("bottom"), border.bottomBorderStyle(), + border.property(FormatPrivate::P_Border_BottomColor).value()); - //Condition DXF formats don't allow diagonal style + // Condition DXF formats don't allow diagonal style if (!isDxf) - writeSubBorder(writer, QStringLiteral("diagonal"), border.diagonalBorderStyle(), border.property(FormatPrivate::P_Border_DiagonalColor).value()); + writeSubBorder(writer, QStringLiteral("diagonal"), border.diagonalBorderStyle(), + border.property(FormatPrivate::P_Border_DiagonalColor).value()); if (isDxf) { -// writeSubBorder(wirter, QStringLiteral("vertical"), ); -// writeSubBorder(writer, QStringLiteral("horizontal"), ); + // writeSubBorder(wirter, QStringLiteral("vertical"), ); + // writeSubBorder(writer, QStringLiteral("horizontal"), ); } - writer.writeEndElement();//border + writer.writeEndElement(); // border } -void Styles::writeSubBorder(QXmlStreamWriter &writer, const QString &type, int style, const XlsxColor &color) const +void Styles::writeSubBorder(QXmlStreamWriter &writer, const QString &type, int style, + const XlsxColor &color) const { if (style == Format::BorderNone) { writer.writeEmptyElement(type); @@ -562,9 +595,9 @@ void Styles::writeSubBorder(QXmlStreamWriter &writer, const QString &type, int s writer.writeStartElement(type); writer.writeAttribute(QStringLiteral("style"), stylesString[style]); - color.saveToXml(writer); //write color element + color.saveToXml(writer); // write color element - writer.writeEndElement();//type + writer.writeEndElement(); // type } void Styles::writeCellXfs(QXmlStreamWriter &writer) const @@ -574,7 +607,8 @@ void Styles::writeCellXfs(QXmlStreamWriter &writer) const foreach (const Format &format, m_xf_formatsList) { int xf_id = 0; writer.writeStartElement(QStringLiteral("xf")); - writer.writeAttribute(QStringLiteral("numFmtId"), QString::number(format.numberFormatIndex())); + writer.writeAttribute(QStringLiteral("numFmtId"), + QString::number(format.numberFormatIndex())); writer.writeAttribute(QStringLiteral("fontId"), QString::number(format.fontIndex())); writer.writeAttribute(QStringLiteral("fillId"), QString::number(format.fillIndex())); writer.writeAttribute(QStringLiteral("borderId"), QString::number(format.borderIndex())); @@ -610,10 +644,12 @@ void Styles::writeCellXfs(QXmlStreamWriter &writer) const writer.writeAttribute(QStringLiteral("horizontal"), QStringLiteral("justify")); break; case Format::AlignHMerge: - writer.writeAttribute(QStringLiteral("horizontal"), QStringLiteral("centerContinuous")); + writer.writeAttribute(QStringLiteral("horizontal"), + QStringLiteral("centerContinuous")); break; case Format::AlignHDistributed: - writer.writeAttribute(QStringLiteral("horizontal"), QStringLiteral("distributed")); + writer.writeAttribute(QStringLiteral("horizontal"), + QStringLiteral("distributed")); break; default: break; @@ -632,7 +668,8 @@ void Styles::writeCellXfs(QXmlStreamWriter &writer) const writer.writeAttribute(QStringLiteral("vertical"), QStringLiteral("justify")); break; case Format::AlignVDistributed: - writer.writeAttribute(QStringLiteral("vertical"), QStringLiteral("distributed")); + writer.writeAttribute(QStringLiteral("vertical"), + QStringLiteral("distributed")); break; default: break; @@ -645,12 +682,13 @@ void Styles::writeCellXfs(QXmlStreamWriter &writer) const if (format.hasProperty(FormatPrivate::P_Alignment_ShinkToFit) && format.shrinkToFit()) writer.writeAttribute(QStringLiteral("shrinkToFit"), QStringLiteral("1")); if (format.hasProperty(FormatPrivate::P_Alignment_Rotation)) - writer.writeAttribute(QStringLiteral("textRotation"), QString::number(format.rotation())); + writer.writeAttribute(QStringLiteral("textRotation"), + QString::number(format.rotation())); } - writer.writeEndElement();//xf + writer.writeEndElement(); // xf } - writer.writeEndElement();//cellXfs + writer.writeEndElement(); // cellXfs } void Styles::writeDxfs(QXmlStreamWriter &writer) const @@ -659,7 +697,7 @@ void Styles::writeDxfs(QXmlStreamWriter &writer) const writer.writeAttribute(QStringLiteral("count"), QString::number(m_dxf_formatsList.size())); foreach (const Format &format, m_dxf_formatsList) writeDxf(writer, format); - writer.writeEndElement(); //dxfs + writer.writeEndElement(); // dxfs } void Styles::writeDxf(QXmlStreamWriter &writer, const Format &format) const @@ -671,7 +709,8 @@ void Styles::writeDxf(QXmlStreamWriter &writer, const Format &format) const if (format.hasNumFmtData()) { writer.writeEmptyElement(QStringLiteral("numFmt")); - writer.writeAttribute(QStringLiteral("numFmtId"), QString::number(format.numberFormatIndex())); + writer.writeAttribute(QStringLiteral("numFmtId"), + QString::number(format.numberFormatIndex())); writer.writeAttribute(QStringLiteral("formatCode"), format.numberFormat()); } @@ -681,25 +720,25 @@ void Styles::writeDxf(QXmlStreamWriter &writer, const Format &format) const if (format.hasBorderData()) writeBorder(writer, format, true); - writer.writeEndElement();//dxf + writer.writeEndElement(); // dxf } void Styles::writeColors(QXmlStreamWriter &writer) const { - if (m_isIndexedColorsDefault) //Don't output the default indexdeColors + if (m_isIndexedColorsDefault) // Don't output the default indexdeColors return; writer.writeStartElement(QStringLiteral("colors")); writer.writeStartElement(QStringLiteral("indexedColors")); - foreach(QColor color, m_indexedColors) { + foreach (QColor color, m_indexedColors) { writer.writeEmptyElement(QStringLiteral("rgbColor")); writer.writeAttribute(QStringLiteral("rgb"), XlsxColor::toARGBString(color)); } - writer.writeEndElement();//indexedColors + writer.writeEndElement(); // indexedColors - writer.writeEndElement();//colors + writer.writeEndElement(); // colors } bool Styles::readNumFmts(QXmlStreamReader &reader) @@ -709,14 +748,15 @@ bool Styles::readNumFmts(QXmlStreamReader &reader) bool hasCount = attributes.hasAttribute(QLatin1String("count")); int count = hasCount ? attributes.value(QLatin1String("count")).toString().toInt() : -1; - //Read utill we find the numFmts end tag or .... - while (!reader.atEnd() && !(reader.tokenType() == QXmlStreamReader::EndElement - && reader.name() == QLatin1String("numFmts"))) { + // Read utill we find the numFmts end tag or .... + while (!reader.atEnd() + && !(reader.tokenType() == QXmlStreamReader::EndElement + && reader.name() == QLatin1String("numFmts"))) { reader.readNextStartElement(); if (reader.tokenType() == QXmlStreamReader::StartElement) { if (reader.name() == QLatin1String("numFmt")) { QXmlStreamAttributes attributes = reader.attributes(); - QSharedPointer fmt (new XlsxFormatNumberData); + QSharedPointer fmt(new XlsxFormatNumberData); fmt->formatIndex = attributes.value(QLatin1String("numFmtId")).toString().toInt(); fmt->formatString = attributes.value(QLatin1String("formatCode")).toString(); if (fmt->formatIndex >= m_nextCustomNumFmtId) @@ -728,7 +768,7 @@ bool Styles::readNumFmts(QXmlStreamReader &reader) } if (reader.hasError()) - qWarning()<formatString); + format.setNumberFormat(numFmtIndex, + m_customNumFmtIdMap[numFmtIndex]->formatString); } } @@ -1079,10 +1142,12 @@ bool Styles::readCellXfs(QXmlStreamReader &reader) if (fontIndex >= m_fontsList.size()) { qDebug("Error read styles.xml, cellXfs fontId"); } else { - bool apply = parseXsdBoolean(xfAttrs.value(QLatin1String("applyFont")).toString()); - if(apply) { + bool apply = + parseXsdBoolean(xfAttrs.value(QLatin1String("applyFont")).toString()); + if (apply) { Format fontFormat = m_fontsList[fontIndex]; - for (int i=FormatPrivate::P_Font_STARTID; i= m_fillsList.size()) { qDebug("Error read styles.xml, cellXfs fillId"); } else { - bool apply = parseXsdBoolean(xfAttrs.value(QLatin1String("applyFill")).toString()); - if(apply) { + bool apply = + parseXsdBoolean(xfAttrs.value(QLatin1String("applyFill")).toString()); + if (apply) { Format fillFormat = m_fillsList[id]; - for (int i=FormatPrivate::P_Fill_STARTID; i= m_bordersList.size()) { qDebug("Error read styles.xml, cellXfs borderId"); } else { - bool apply = parseXsdBoolean(xfAttrs.value(QLatin1String("applyBorder")).toString()); - if(apply) { + bool apply = + parseXsdBoolean(xfAttrs.value(QLatin1String("applyBorder")).toString()); + if (apply) { Format borderFormat = m_bordersList[id]; - for (int i=FormatPrivate::P_Border_STARTID; i alignStringMap; if (alignStringMap.isEmpty()) { alignStringMap.insert(QStringLiteral("left"), Format::AlignLeft); - alignStringMap.insert(QStringLiteral("center"), Format::AlignHCenter); + alignStringMap.insert(QStringLiteral("center"), + Format::AlignHCenter); alignStringMap.insert(QStringLiteral("right"), Format::AlignRight); - alignStringMap.insert(QStringLiteral("justify"), Format::AlignHJustify); - alignStringMap.insert(QStringLiteral("centerContinuous"), Format::AlignHMerge); - alignStringMap.insert(QStringLiteral("distributed"), Format::AlignHDistributed); + alignStringMap.insert(QStringLiteral("justify"), + Format::AlignHJustify); + alignStringMap.insert(QStringLiteral("centerContinuous"), + Format::AlignHMerge); + alignStringMap.insert(QStringLiteral("distributed"), + Format::AlignHDistributed); } QString str = alignAttrs.value(QLatin1String("horizontal")).toString(); if (alignStringMap.contains(str)) @@ -1147,9 +1221,12 @@ bool Styles::readCellXfs(QXmlStreamReader &reader) static QMap alignStringMap; if (alignStringMap.isEmpty()) { alignStringMap.insert(QStringLiteral("top"), Format::AlignTop); - alignStringMap.insert(QStringLiteral("center"), Format::AlignVCenter); - alignStringMap.insert(QStringLiteral("justify"), Format::AlignVJustify); - alignStringMap.insert(QStringLiteral("distributed"), Format::AlignVDistributed); + alignStringMap.insert(QStringLiteral("center"), + Format::AlignVCenter); + alignStringMap.insert(QStringLiteral("justify"), + Format::AlignVJustify); + alignStringMap.insert(QStringLiteral("distributed"), + Format::AlignVDistributed); } QString str = alignAttrs.value(QLatin1String("vertical")).toString(); if (alignStringMap.contains(str)) @@ -1157,12 +1234,14 @@ bool Styles::readCellXfs(QXmlStreamReader &reader) } if (alignAttrs.hasAttribute(QLatin1String("indent"))) { - int indent = alignAttrs.value(QLatin1String("indent")).toString().toInt(); + int indent = + alignAttrs.value(QLatin1String("indent")).toString().toInt(); format.setIndent(indent); } if (alignAttrs.hasAttribute(QLatin1String("textRotation"))) { - int rotation = alignAttrs.value(QLatin1String("textRotation")).toString().toInt(); + int rotation = + alignAttrs.value(QLatin1String("textRotation")).toString().toInt(); format.setRotation(rotation); } @@ -1171,7 +1250,6 @@ bool Styles::readCellXfs(QXmlStreamReader &reader) if (alignAttrs.hasAttribute(QLatin1String("shrinkToFit"))) format.setShrinkToFit(true); - } } @@ -1181,7 +1259,7 @@ bool Styles::readCellXfs(QXmlStreamReader &reader) } if (reader.hasError()) - qWarning()<= m_indexedColors.size()) @@ -1331,4 +1421,4 @@ QColor Styles::getColorByIndex(int idx) return m_indexedColors[idx]; } -} //namespace QXlsx +} // namespace QXlsx diff --git a/src/xlsx/xlsxstyles_p.h b/src/xlsx/xlsxstyles_p.h index 7567e23..13af4a2 100755 --- a/src/xlsx/xlsxstyles_p.h +++ b/src/xlsx/xlsxstyles_p.h @@ -58,7 +58,10 @@ class XlsxColor; struct XlsxFormatNumberData { - XlsxFormatNumberData() : formatIndex(0) {} + XlsxFormatNumberData() + : formatIndex(0) + { + } int formatIndex; QString formatString; @@ -69,9 +72,9 @@ class XLSX_AUTOTEST_EXPORT Styles : public AbstractOOXmlFile public: Styles(CreateFlag flag); ~Styles(); - void addXfFormat(const Format &format, bool force=false); + void addXfFormat(const Format &format, bool force = false); Format xfFormat(int idx) const; - void addDxfFormat(const Format &format, bool force=false); + void addDxfFormat(const Format &format, bool force = false); Format dxfFormat(int idx) const; void saveToXmlFile(QIODevice *device) const; @@ -92,7 +95,8 @@ private: void writeFill(QXmlStreamWriter &writer, const Format &fill, bool isDxf = false) const; void writeBorders(QXmlStreamWriter &writer) const; void writeBorder(QXmlStreamWriter &writer, const Format &border, bool isDxf = false) const; - void writeSubBorder(QXmlStreamWriter &writer, const QString &type, int style, const XlsxColor &color) const; + void writeSubBorder(QXmlStreamWriter &writer, const QString &type, int style, + const XlsxColor &color) const; void writeCellXfs(QXmlStreamWriter &writer) const; void writeDxfs(QXmlStreamWriter &writer) const; void writeDxf(QXmlStreamWriter &writer, const Format &format) const; @@ -105,7 +109,8 @@ private: bool readFill(QXmlStreamReader &reader, Format &format); bool readBorders(QXmlStreamReader &reader); bool readBorder(QXmlStreamReader &reader, Format &format); - bool readSubBorder(QXmlStreamReader &reader, const QString &name, Format::BorderStyle &style, XlsxColor &color); + bool readSubBorder(QXmlStreamReader &reader, const QString &name, Format::BorderStyle &style, + XlsxColor &color); bool readCellXfs(QXmlStreamReader &reader); bool readDxfs(QXmlStreamReader &reader); bool readDxf(QXmlStreamReader &reader); @@ -113,8 +118,8 @@ private: bool readIndexedColors(QXmlStreamReader &reader); QHash m_builtinNumFmtsHash; - QMap > m_customNumFmtIdMap; - QHash > m_customNumFmtsHash; + QMap> m_customNumFmtIdMap; + QHash> m_customNumFmtsHash; int m_nextCustomNumFmtId; QList m_fontsList; QList m_fillsList; @@ -134,6 +139,5 @@ private: bool m_emptyFormatAdded; }; - } #endif // XLSXSTYLES_H diff --git a/src/xlsx/xlsxtheme.cpp b/src/xlsx/xlsxtheme.cpp index d0c0758..841cc9c 100755 --- a/src/xlsx/xlsxtheme.cpp +++ b/src/xlsx/xlsxtheme.cpp @@ -28,181 +28,198 @@ namespace QXlsx { const char *defaultXmlData = - "\n" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - ; + "\n" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + ""; Theme::Theme(CreateFlag flag) - :AbstractOOXmlFile(flag) + : AbstractOOXmlFile(flag) { } @@ -233,5 +250,4 @@ bool Theme::loadFromXmlFile(QIODevice *device) xmlData = device->readAll(); return true; } - } diff --git a/src/xlsx/xlsxtheme_p.h b/src/xlsx/xlsxtheme_p.h index 0b183b2..f68bbd0 100755 --- a/src/xlsx/xlsxtheme_p.h +++ b/src/xlsx/xlsxtheme_p.h @@ -54,6 +54,5 @@ public: QByteArray xmlData; }; - } #endif // XLSXTHEME_H diff --git a/src/xlsx/xlsxutility.cpp b/src/xlsx/xlsxutility.cpp index d2abadb..a7abdfc 100755 --- a/src/xlsx/xlsxutility.cpp +++ b/src/xlsx/xlsxutility.cpp @@ -49,9 +49,9 @@ QStringList splitPath(const QString &path) { int idx = path.lastIndexOf(QLatin1Char('/')); if (idx == -1) - return QStringList()<= 0x050200 - if (dt.isDaylightTime()) // Add one hour if the date is Daylight + if (dt.isDaylightTime()) // Add one hour if the date is Daylight excel_time += 1.0 / 24.0; #endif - if (!is1904 && excel_time > 59) {//31+28 - //Account for Excel erroneously treating 1900 as a leap year. + if (!is1904 && excel_time > 59) { // 31+28 + // Account for Excel erroneously treating 1900 as a leap year. excel_time += 1; } @@ -89,7 +89,7 @@ double datetimeToNumber(const QDateTime &dt, bool is1904) double timeToNumber(const QTime &time) { - return QTime(0,0).msecsTo(time) / (1000*60*60*24.0); + return QTime(0, 0).msecsTo(time) / (1000 * 60 * 60 * 24.0); } QDateTime datetimeFromNumber(double num, bool is1904) @@ -97,8 +97,8 @@ QDateTime datetimeFromNumber(double num, bool is1904) if (!is1904 && num > 60) num = num - 1; - qint64 msecs = static_cast(num * 1000*60*60*24.0 + 0.5); - QDateTime epoch(is1904 ? QDate(1904, 1, 1): QDate(1899, 12, 31), QTime(0,0)); + qint64 msecs = static_cast(num * 1000 * 60 * 60 * 24.0 + 0.5); + QDateTime epoch(is1904 ? QDate(1904, 1, 1) : QDate(1899, 12, 31), QTime(0, 0)); QDateTime dt = epoch.addMSecs(msecs); @@ -127,16 +127,17 @@ QString createSafeSheetName(const QString &nameProposal) return QString(); QString ret = nameProposal; - if (nameProposal.length() > 2 && nameProposal.startsWith(QLatin1Char('\'')) && nameProposal.endsWith(QLatin1Char('\''))) + if (nameProposal.length() > 2 && nameProposal.startsWith(QLatin1Char('\'')) + && nameProposal.endsWith(QLatin1Char('\''))) ret = unescapeSheetName(ret); - //Replace invalid chars with space. + // Replace invalid chars with space. if (nameProposal.contains(QRegularExpression(QStringLiteral("[/\\\\?*\\][:]")))) ret.replace(QRegularExpression(QStringLiteral("[/\\\\?*\\][:]")), QStringLiteral(" ")); if (ret.startsWith(QLatin1Char('\''))) ret[0] = QLatin1Char(' '); if (ret.endsWith(QLatin1Char('\''))) - ret[ret.size()-1] = QLatin1Char(' '); + ret[ret.size() - 1] = QLatin1Char(' '); if (ret.size() > 31) ret = ret.left(31); @@ -144,18 +145,19 @@ QString createSafeSheetName(const QString &nameProposal) } /* - * When sheetName contains space or apostrophe, escaped is needed by cellFormula/definedName/chartSerials. + * When sheetName contains space or apostrophe, escaped is needed by + * cellFormula/definedName/chartSerials. */ QString escapeSheetName(const QString &sheetName) { - //Already escaped. + // Already escaped. Q_ASSERT(!sheetName.startsWith(QLatin1Char('\'')) && !sheetName.endsWith(QLatin1Char('\''))); - //These is no need to escape + // These is no need to escape if (!sheetName.contains(QRegularExpression(QStringLiteral("[ +\\-,%^=<>'&]")))) return sheetName; - //OK, escape is needed. + // OK, escape is needed. QString name = sheetName; name.replace(QLatin1Char('\''), QLatin1String("\'\'")); return QLatin1Char('\'') + name + QLatin1Char('\''); @@ -165,9 +167,10 @@ QString escapeSheetName(const QString &sheetName) */ QString unescapeSheetName(const QString &sheetName) { - Q_ASSERT(sheetName.length() > 2 && sheetName.startsWith(QLatin1Char('\'')) && sheetName.endsWith(QLatin1Char('\''))); + Q_ASSERT(sheetName.length() > 2 && sheetName.startsWith(QLatin1Char('\'')) + && sheetName.endsWith(QLatin1Char('\''))); - QString name = sheetName.mid(1, sheetName.length()-2); + QString name = sheetName.mid(1, sheetName.length() - 2); name.replace(QLatin1String("\'\'"), QLatin1String("\'")); return name; } @@ -178,7 +181,7 @@ QString unescapeSheetName(const QString &sheetName) bool isSpaceReserveNeeded(const QString &s) { QString spaces(QStringLiteral(" \t\n\r")); - return !s.isEmpty() && (spaces.contains(s.at(0))||spaces.contains(s.at(s.length()-1))); + return !s.isEmpty() && (spaces.contains(s.at(0)) || spaces.contains(s.at(s.length() - 1))); } /* @@ -192,14 +195,15 @@ bool isSpaceReserveNeeded(const QString &s) * * For long run, we need a formula parser. */ -QString convertSharedFormula(const QString &rootFormula, const CellReference &rootCell, const CellReference &cell) +QString convertSharedFormula(const QString &rootFormula, const CellReference &rootCell, + const CellReference &cell) { - //Find all the "$?[A-Z]+$?[0-9]+" patterns in the rootFormula. - QList > segments; + // Find all the "$?[A-Z]+$?[0-9]+" patterns in the rootFormula. + QList> segments; QString segment; bool inQuote = false; - enum RefState{INVALID, PRE_AZ, AZ, PRE_09, _09}; + enum RefState { INVALID, PRE_AZ, AZ, PRE_09, _09 }; RefState refState = INVALID; int refFlag = 0; // 0x00, 0x01, 0x02, 0x03 ==> A1, $A1, A$1, $A$1 foreach (QChar ch, rootFormula) { @@ -218,21 +222,21 @@ QString convertSharedFormula(const QString &rootFormula, const CellReference &ro refState = PRE_09; refFlag |= 0x02; } else { - segments.append(qMakePair(segment, refState==_09 ? refFlag : -1)); - segment = QString(ch); //Start new segment. + segments.append(qMakePair(segment, refState == _09 ? refFlag : -1)); + segment = QString(ch); // Start new segment. refState = PRE_AZ; refFlag = 0x01; } - } else if (ch >= QLatin1Char('A') && ch <=QLatin1Char('Z')) { + } else if (ch >= QLatin1Char('A') && ch <= QLatin1Char('Z')) { if (refState == PRE_AZ || refState == AZ) { segment.append(ch); } else { - segments.append(qMakePair(segment, refState==_09 ? refFlag : -1)); - segment = QString(ch); //Start new segment. + segments.append(qMakePair(segment, refState == _09 ? refFlag : -1)); + segment = QString(ch); // Start new segment. refFlag = 0x00; } refState = AZ; - } else if (ch >= QLatin1Char('0') && ch <=QLatin1Char('9')) { + } else if (ch >= QLatin1Char('0') && ch <= QLatin1Char('9')) { segment.append(ch); if (refState == AZ || refState == PRE_09 || refState == _09) @@ -242,7 +246,7 @@ QString convertSharedFormula(const QString &rootFormula, const CellReference &ro } else { if (refState == _09) { segments.append(qMakePair(segment, refFlag)); - segment = QString(ch); //Start new segment. + segment = QString(ch); // Start new segment. } else { segment.append(ch); } @@ -252,25 +256,26 @@ QString convertSharedFormula(const QString &rootFormula, const CellReference &ro } if (!segment.isEmpty()) - segments.append(qMakePair(segment, refState==_09 ? refFlag : -1)); + segments.append(qMakePair(segment, refState == _09 ? refFlag : -1)); - //Replace "A1", "$A1", "A$1" segment with proper one. + // Replace "A1", "$A1", "A$1" segment with proper one. QStringList result; typedef QPair PairType; foreach (PairType p, segments) { - //qDebug()< (new SharedStrings(flag)); + sharedStrings = QSharedPointer(new SharedStrings(flag)); styles = QSharedPointer(new Styles(flag)); theme = QSharedPointer(new Theme(flag)); @@ -71,7 +71,6 @@ WorkbookPrivate::WorkbookPrivate(Workbook *q, Workbook::CreateFlag flag) : Workbook::Workbook(CreateFlag flag) : AbstractOOXmlFile(new WorkbookPrivate(this, flag)) { - } Workbook::~Workbook() @@ -163,18 +162,19 @@ void Workbook::setDefaultDateFormat(const QString &format) * \param scope The name of one worksheet, or empty which means golbal scope. * \return Return false if the name invalid. */ -bool Workbook::defineName(const QString &name, const QString &formula, const QString &comment, const QString &scope) +bool Workbook::defineName(const QString &name, const QString &formula, const QString &comment, + const QString &scope) { Q_D(Workbook); - //Remove the = sign from the formula if it exists. + // Remove the = sign from the formula if it exists. QString formulaString = formula; if (formulaString.startsWith(QLatin1Char('='))) formulaString = formula.mid(1); - int id=-1; + int id = -1; if (!scope.isEmpty()) { - for (int i=0; isheets.size(); ++i) { + for (int i = 0; i < d->sheets.size(); ++i) { if (d->sheets[i]->sheetName() == scope) { id = d->sheets[i]->sheetId(); break; @@ -210,7 +210,7 @@ AbstractSheet *Workbook::addSheet(const QString &name, int sheetId, AbstractShee Q_D(Workbook); if (sheetId > d->last_sheet_id) d->last_sheet_id = sheetId; - AbstractSheet *sheet=0; + AbstractSheet *sheet = 0; if (type == AbstractSheet::ST_WorkSheet) { sheet = new Worksheet(name, sheetId, this, F_LoadFromExists); } else if (type == AbstractSheet::ST_ChartSheet) { @@ -229,7 +229,7 @@ AbstractSheet *Workbook::insertSheet(int index, const QString &name, AbstractShe Q_D(Workbook); QString sheetName = createSafeSheetName(name); if (!sheetName.isEmpty()) { - //If user given an already in-used name, we should not continue any more! + // If user given an already in-used name, we should not continue any more! if (d->sheetNames.contains(sheetName)) return 0; } else { @@ -269,7 +269,7 @@ AbstractSheet *Workbook::activeSheet() const { Q_D(const Workbook); if (d->sheets.isEmpty()) - const_cast(this)->addSheet(); + const_cast(this)->addSheet(); return d->sheets[d->activesheetIndex].data(); } @@ -277,7 +277,7 @@ bool Workbook::setActiveSheet(int index) { Q_D(Workbook); if (index < 0 || index >= d->sheets.size()) { - //warning + // warning return false; } d->activesheetIndex = index; @@ -294,8 +294,8 @@ bool Workbook::renameSheet(int index, const QString &newName) if (index < 0 || index >= d->sheets.size()) return false; - //If user given an already in-used name, return false - for (int i=0; isheets.size(); ++i) { + // If user given an already in-used name, return false + for (int i = 0; i < d->sheets.size(); ++i) { if (d->sheets[i]->sheetName() == name) return false; } @@ -352,20 +352,21 @@ bool Workbook::copySheet(int index, const QString &newName) QString worksheetName = createSafeSheetName(newName); if (!newName.isEmpty()) { - //If user given an already in-used name, we should not continue any more! + // If user given an already in-used name, we should not continue any more! if (d->sheetNames.contains(newName)) return false; } else { int copy_index = 1; do { ++copy_index; - worksheetName = QStringLiteral("%1(%2)").arg(d->sheets[index]->sheetName()).arg(copy_index); + worksheetName = + QStringLiteral("%1(%2)").arg(d->sheets[index]->sheetName()).arg(copy_index); } while (d->sheetNames.contains(worksheetName)); } ++d->last_sheet_id; AbstractSheet *sheet = d->sheets[index]->copy(worksheetName, d->last_sheet_id); - d->sheets.append(QSharedPointer (sheet)); + d->sheets.append(QSharedPointer(sheet)); d->sheetNames.append(sheet->sheetName()); return false; @@ -418,10 +419,10 @@ QList Workbook::drawings() { Q_D(Workbook); QList ds; - for (int i=0; isheets.size(); ++i) { + for (int i = 0; i < d->sheets.size(); ++i) { QSharedPointer sheet = d->sheets[i]; if (sheet->drawing()) - ds.append(sheet->drawing()); + ds.append(sheet->drawing()); } return ds; @@ -430,11 +431,11 @@ QList Workbook::drawings() /*! * \internal */ -QList > Workbook::getSheetsByTypes(AbstractSheet::SheetType type) const +QList> Workbook::getSheetsByTypes(AbstractSheet::SheetType type) const { Q_D(const Workbook); - QList > list; - for (int i=0; isheets.size(); ++i) { + QList> list; + for (int i = 0; i < d->sheets.size(); ++i) { if (d->sheets[i]->sheetType() == type) list.append(d->sheets[i]); } @@ -452,15 +453,20 @@ void Workbook::saveToXmlFile(QIODevice *device) const writer.writeStartDocument(QStringLiteral("1.0"), true); writer.writeStartElement(QStringLiteral("workbook")); - writer.writeAttribute(QStringLiteral("xmlns"), QStringLiteral("http://schemas.openxmlformats.org/spreadsheetml/2006/main")); - writer.writeAttribute(QStringLiteral("xmlns:r"), QStringLiteral("http://schemas.openxmlformats.org/officeDocument/2006/relationships")); + writer.writeAttribute( + QStringLiteral("xmlns"), + QStringLiteral("http://schemas.openxmlformats.org/spreadsheetml/2006/main")); + writer.writeAttribute( + QStringLiteral("xmlns:r"), + QStringLiteral("http://schemas.openxmlformats.org/officeDocument/2006/relationships")); writer.writeEmptyElement(QStringLiteral("fileVersion")); writer.writeAttribute(QStringLiteral("appName"), QStringLiteral("xl")); writer.writeAttribute(QStringLiteral("lastEdited"), QStringLiteral("4")); writer.writeAttribute(QStringLiteral("lowestEdited"), QStringLiteral("4")); writer.writeAttribute(QStringLiteral("rupBuild"), QStringLiteral("4505")); -// writer.writeAttribute(QStringLiteral("codeName"), QStringLiteral("{37E998C4-C9E5-D4B9-71C8-EB1FF731991C}")); + // writer.writeAttribute(QStringLiteral("codeName"), + // QStringLiteral("{37E998C4-C9E5-D4B9-71C8-EB1FF731991C}")); writer.writeEmptyElement(QStringLiteral("workbookPr")); if (d->date1904) @@ -473,19 +479,19 @@ void Workbook::saveToXmlFile(QIODevice *device) const writer.writeAttribute(QStringLiteral("yWindow"), QString::number(d->y_window)); writer.writeAttribute(QStringLiteral("windowWidth"), QString::number(d->window_width)); writer.writeAttribute(QStringLiteral("windowHeight"), QString::number(d->window_height)); - //Store the firstSheet when it isn't the default - //For example, when "the first sheet 0 is hidden", the first sheet will be 1 + // Store the firstSheet when it isn't the default + // For example, when "the first sheet 0 is hidden", the first sheet will be 1 if (d->firstsheet > 0) writer.writeAttribute(QStringLiteral("firstSheet"), QString::number(d->firstsheet + 1)); - //Store the activeTab when it isn't the first sheet + // Store the activeTab when it isn't the first sheet if (d->activesheetIndex > 0) writer.writeAttribute(QStringLiteral("activeTab"), QString::number(d->activesheetIndex)); - writer.writeEndElement();//bookViews + writer.writeEndElement(); // bookViews writer.writeStartElement(QStringLiteral("sheets")); int worksheetIndex = 0; int chartsheetIndex = 0; - for (int i=0; isheets.size(); ++i) { + for (int i = 0; i < d->sheets.size(); ++i) { QSharedPointer sheet = d->sheets[i]; writer.writeEmptyElement(QStringLiteral("sheet")); writer.writeAttribute(QStringLiteral("name"), sheet->sheetName()); @@ -496,22 +502,30 @@ void Workbook::saveToXmlFile(QIODevice *device) const writer.writeAttribute(QStringLiteral("state"), QStringLiteral("veryHidden")); if (sheet->sheetType() == AbstractSheet::ST_WorkSheet) - d->relationships->addDocumentRelationship(QStringLiteral("/worksheet"), QStringLiteral("worksheets/sheet%1.xml").arg(++worksheetIndex)); + d->relationships->addDocumentRelationship( + QStringLiteral("/worksheet"), + QStringLiteral("worksheets/sheet%1.xml").arg(++worksheetIndex)); else - d->relationships->addDocumentRelationship(QStringLiteral("/chartsheet"), QStringLiteral("chartsheets/sheet%1.xml").arg(++chartsheetIndex)); + d->relationships->addDocumentRelationship( + QStringLiteral("/chartsheet"), + QStringLiteral("chartsheets/sheet%1.xml").arg(++chartsheetIndex)); - writer.writeAttribute(QStringLiteral("r:id"), QStringLiteral("rId%1").arg(d->relationships->count())); + writer.writeAttribute(QStringLiteral("r:id"), + QStringLiteral("rId%1").arg(d->relationships->count())); } - writer.writeEndElement();//sheets + writer.writeEndElement(); // sheets if (d->externalLinks.size() > 0) { writer.writeStartElement(QStringLiteral("externalReferences")); - for (int i=0; iexternalLinks.size(); ++i) { + for (int i = 0; i < d->externalLinks.size(); ++i) { writer.writeEmptyElement(QStringLiteral("externalReference")); - d->relationships->addDocumentRelationship(QStringLiteral("/externalLink"), QStringLiteral("externalLinks/externalLink%1.xml").arg(i+1)); - writer.writeAttribute(QStringLiteral("r:id"), QStringLiteral("rId%1").arg(d->relationships->count())); + d->relationships->addDocumentRelationship( + QStringLiteral("/externalLink"), + QStringLiteral("externalLinks/externalLink%1.xml").arg(i + 1)); + writer.writeAttribute(QStringLiteral("r:id"), + QStringLiteral("rId%1").arg(d->relationships->count())); } - writer.writeEndElement();//externalReferences + writer.writeEndElement(); // externalReferences } if (!d->definedNamesList.isEmpty()) { @@ -522,8 +536,8 @@ void Workbook::saveToXmlFile(QIODevice *device) const if (!data.comment.isEmpty()) writer.writeAttribute(QStringLiteral("comment"), data.comment); if (data.sheetId != -1) { - //find the local index of the sheet. - for (int i=0; isheets.size(); ++i) { + // find the local index of the sheet. + for (int i = 0; i < d->sheets.size(); ++i) { if (d->sheets[i]->sheetId() == data.sheetId) { writer.writeAttribute(QStringLiteral("localSheetId"), QString::number(i)); break; @@ -531,22 +545,25 @@ void Workbook::saveToXmlFile(QIODevice *device) const } } writer.writeCharacters(data.formula); - writer.writeEndElement();//definedName + writer.writeEndElement(); // definedName } - writer.writeEndElement();//definedNames + writer.writeEndElement(); // definedNames } writer.writeStartElement(QStringLiteral("calcPr")); writer.writeAttribute(QStringLiteral("calcId"), QStringLiteral("124519")); - writer.writeEndElement(); //calcPr + writer.writeEndElement(); // calcPr - writer.writeEndElement();//workbook + writer.writeEndElement(); // workbook writer.writeEndDocument(); - d->relationships->addDocumentRelationship(QStringLiteral("/theme"), QStringLiteral("theme/theme1.xml")); - d->relationships->addDocumentRelationship(QStringLiteral("/styles"), QStringLiteral("styles.xml")); + d->relationships->addDocumentRelationship(QStringLiteral("/theme"), + QStringLiteral("theme/theme1.xml")); + d->relationships->addDocumentRelationship(QStringLiteral("/styles"), + QStringLiteral("styles.xml")); if (!sharedStrings()->isEmpty()) - d->relationships->addDocumentRelationship(QStringLiteral("/sharedStrings"), QStringLiteral("sharedStrings.xml")); + d->relationships->addDocumentRelationship(QStringLiteral("/sharedStrings"), + QStringLiteral("sharedStrings.xml")); } bool Workbook::loadFromXmlFile(QIODevice *device) @@ -555,88 +572,97 @@ bool Workbook::loadFromXmlFile(QIODevice *device) QXmlStreamReader reader(device); while (!reader.atEnd()) { - QXmlStreamReader::TokenType token = reader.readNext(); - if (token == QXmlStreamReader::StartElement) { - if (reader.name() == QLatin1String("sheet")) { - QXmlStreamAttributes attributes = reader.attributes(); - const QString name = attributes.value(QLatin1String("name")).toString(); - int sheetId = attributes.value(QLatin1String("sheetId")).toString().toInt(); - const QString rId = attributes.value(QLatin1String("r:id")).toString(); - const QStringRef &stateString = attributes.value(QLatin1String("state")); - AbstractSheet::SheetState state = AbstractSheet::SS_Visible; - if (stateString == QLatin1String("hidden")) - state = AbstractSheet::SS_Hidden; - else if (stateString == QLatin1String("veryHidden")) - state = AbstractSheet::SS_VeryHidden; + QXmlStreamReader::TokenType token = reader.readNext(); + if (token == QXmlStreamReader::StartElement) { + if (reader.name() == QLatin1String("sheet")) { + QXmlStreamAttributes attributes = reader.attributes(); + const QString name = attributes.value(QLatin1String("name")).toString(); + int sheetId = attributes.value(QLatin1String("sheetId")).toString().toInt(); + const QString rId = attributes.value(QLatin1String("r:id")).toString(); + const QStringRef &stateString = attributes.value(QLatin1String("state")); + AbstractSheet::SheetState state = AbstractSheet::SS_Visible; + if (stateString == QLatin1String("hidden")) + state = AbstractSheet::SS_Hidden; + else if (stateString == QLatin1String("veryHidden")) + state = AbstractSheet::SS_VeryHidden; - XlsxRelationship relationship = d->relationships->getRelationshipById(rId); + XlsxRelationship relationship = d->relationships->getRelationshipById(rId); - AbstractSheet::SheetType type = AbstractSheet::ST_WorkSheet; - if (relationship.type.endsWith(QLatin1String("/worksheet"))) - type = AbstractSheet::ST_WorkSheet; - else if (relationship.type.endsWith(QLatin1String("/chartsheet"))) - type = AbstractSheet::ST_ChartSheet; - else if (relationship.type.endsWith(QLatin1String("/dialogsheet"))) - type = AbstractSheet::ST_DialogSheet; - else if (relationship.type.endsWith(QLatin1String("/xlMacrosheet"))) - type = AbstractSheet::ST_MacroSheet; - else - qWarning("unknown sheet type"); + AbstractSheet::SheetType type = AbstractSheet::ST_WorkSheet; + if (relationship.type.endsWith(QLatin1String("/worksheet"))) + type = AbstractSheet::ST_WorkSheet; + else if (relationship.type.endsWith(QLatin1String("/chartsheet"))) + type = AbstractSheet::ST_ChartSheet; + else if (relationship.type.endsWith(QLatin1String("/dialogsheet"))) + type = AbstractSheet::ST_DialogSheet; + else if (relationship.type.endsWith(QLatin1String("/xlMacrosheet"))) + type = AbstractSheet::ST_MacroSheet; + else + qWarning("unknown sheet type"); - AbstractSheet *sheet = addSheet(name, sheetId, type); - sheet->setSheetState(state); - const QString fullPath = QDir::cleanPath(splitPath(filePath())[0] +QLatin1String("/")+ relationship.target); - sheet->setFilePath(fullPath); - } else if (reader.name() == QLatin1String("workbookPr")) { + AbstractSheet *sheet = addSheet(name, sheetId, type); + sheet->setSheetState(state); + const QString fullPath = QDir::cleanPath( + splitPath(filePath())[0] + QLatin1String("/") + relationship.target); + sheet->setFilePath(fullPath); + } else if (reader.name() == QLatin1String("workbookPr")) { QXmlStreamAttributes attrs = reader.attributes(); if (attrs.hasAttribute(QLatin1String("date1904"))) d->date1904 = true; - } else if (reader.name() == QLatin1String("bookviews")) { - while (!(reader.name() == QLatin1String("bookviews") && reader.tokenType() == QXmlStreamReader::EndElement)) { + } else if (reader.name() == QLatin1String("bookviews")) { + while (!(reader.name() == QLatin1String("bookviews") + && reader.tokenType() == QXmlStreamReader::EndElement)) { reader.readNextStartElement(); if (reader.tokenType() == QXmlStreamReader::StartElement) { if (reader.name() == QLatin1String("workbookView")) { QXmlStreamAttributes attrs = reader.attributes(); if (attrs.hasAttribute(QLatin1String("xWindow"))) - d->x_window = attrs.value(QLatin1String("xWindow")).toString().toInt(); + d->x_window = + attrs.value(QLatin1String("xWindow")).toString().toInt(); if (attrs.hasAttribute(QLatin1String("yWindow"))) - d->y_window = attrs.value(QLatin1String("yWindow")).toString().toInt(); + d->y_window = + attrs.value(QLatin1String("yWindow")).toString().toInt(); if (attrs.hasAttribute(QLatin1String("windowWidth"))) - d->window_width = attrs.value(QLatin1String("windowWidth")).toString().toInt(); + d->window_width = + attrs.value(QLatin1String("windowWidth")).toString().toInt(); if (attrs.hasAttribute(QLatin1String("windowHeight"))) - d->window_height = attrs.value(QLatin1String("windowHeight")).toString().toInt(); + d->window_height = + attrs.value(QLatin1String("windowHeight")).toString().toInt(); if (attrs.hasAttribute(QLatin1String("firstSheet"))) - d->firstsheet = attrs.value(QLatin1String("firstSheet")).toString().toInt(); + d->firstsheet = + attrs.value(QLatin1String("firstSheet")).toString().toInt(); if (attrs.hasAttribute(QLatin1String("activeTab"))) - d->activesheetIndex = attrs.value(QLatin1String("activeTab")).toString().toInt(); + d->activesheetIndex = + attrs.value(QLatin1String("activeTab")).toString().toInt(); } } } - } else if (reader.name() == QLatin1String("externalReference")) { - QXmlStreamAttributes attributes = reader.attributes(); - const QString rId = attributes.value(QLatin1String("r:id")).toString(); - XlsxRelationship relationship = d->relationships->getRelationshipById(rId); + } else if (reader.name() == QLatin1String("externalReference")) { + QXmlStreamAttributes attributes = reader.attributes(); + const QString rId = attributes.value(QLatin1String("r:id")).toString(); + XlsxRelationship relationship = d->relationships->getRelationshipById(rId); - QSharedPointer link(new SimpleOOXmlFile(F_LoadFromExists)); - const QString fullPath = QDir::cleanPath(splitPath(filePath())[0] +QLatin1String("/")+ relationship.target); - link->setFilePath(fullPath); - d->externalLinks.append(link); - } else if (reader.name() == QLatin1String("definedName")) { - QXmlStreamAttributes attrs = reader.attributes(); - XlsxDefineNameData data; + QSharedPointer link(new SimpleOOXmlFile(F_LoadFromExists)); + const QString fullPath = QDir::cleanPath( + splitPath(filePath())[0] + QLatin1String("/") + relationship.target); + link->setFilePath(fullPath); + d->externalLinks.append(link); + } else if (reader.name() == QLatin1String("definedName")) { + QXmlStreamAttributes attrs = reader.attributes(); + XlsxDefineNameData data; - data.name = attrs.value(QLatin1String("name")).toString(); - if (attrs.hasAttribute(QLatin1String("comment"))) - data.comment = attrs.value(QLatin1String("comment")).toString(); - if (attrs.hasAttribute(QLatin1String("localSheetId"))) { - int localId = attrs.value(QLatin1String("localSheetId")).toString().toInt(); - int sheetId = d->sheets.at(localId)->sheetId(); - data.sheetId = sheetId; - } - data.formula = reader.readElementText(); - d->definedNamesList.append(data); - } - } + data.name = attrs.value(QLatin1String("name")).toString(); + if (attrs.hasAttribute(QLatin1String("comment"))) + data.comment = attrs.value(QLatin1String("comment")).toString(); + if (attrs.hasAttribute(QLatin1String("localSheetId"))) { + int localId = attrs.value(QLatin1String("localSheetId")).toString().toInt(); + int sheetId = d->sheets.at(localId)->sheetId(); + data.sheetId = sheetId; + } + data.formula = reader.readElementText(); + d->definedNamesList.append(data); + } + } } return true; } @@ -644,7 +670,7 @@ bool Workbook::loadFromXmlFile(QIODevice *device) /*! * \internal */ -QList > Workbook::mediaFiles() const +QList> Workbook::mediaFiles() const { Q_D(const Workbook); @@ -658,7 +684,7 @@ void Workbook::addMediaFile(QSharedPointer media, bool force) { Q_D(Workbook); if (!force) { - for (int i=0; imediaFiles.size(); ++i) { + for (int i = 0; i < d->mediaFiles.size(); ++i) { if (d->mediaFiles[i]->hashKey() == media->hashKey()) { media->setIndex(i); return; @@ -672,7 +698,7 @@ void Workbook::addMediaFile(QSharedPointer media, bool force) /*! * \internal */ -QList > Workbook::chartFiles() const +QList> Workbook::chartFiles() const { Q_D(const Workbook); diff --git a/src/xlsx/xlsxworkbook.h b/src/xlsx/xlsxworkbook.h index 464f046..4665a37 100755 --- a/src/xlsx/xlsxworkbook.h +++ b/src/xlsx/xlsxworkbook.h @@ -58,34 +58,37 @@ public: int sheetCount() const; AbstractSheet *sheet(int index) const; - AbstractSheet *addSheet(const QString &name = QString(), AbstractSheet::SheetType type = AbstractSheet::ST_WorkSheet); - AbstractSheet *insertSheet(int index, const QString &name = QString(), AbstractSheet::SheetType type = AbstractSheet::ST_WorkSheet); + AbstractSheet *addSheet(const QString &name = QString(), + AbstractSheet::SheetType type = AbstractSheet::ST_WorkSheet); + AbstractSheet *insertSheet(int index, const QString &name = QString(), + AbstractSheet::SheetType type = AbstractSheet::ST_WorkSheet); bool renameSheet(int index, const QString &name); bool deleteSheet(int index); - bool copySheet(int index, const QString &newName=QString()); + bool copySheet(int index, const QString &newName = QString()); bool moveSheet(int srcIndex, int distIndex); AbstractSheet *activeSheet() const; bool setActiveSheet(int index); -// void addChart(); - bool defineName(const QString &name, const QString &formula, const QString &comment=QString(), const QString &scope=QString()); + // void addChart(); + bool defineName(const QString &name, const QString &formula, const QString &comment = QString(), + const QString &scope = QString()); bool isDate1904() const; void setDate1904(bool date1904); bool isStringsToNumbersEnabled() const; - void setStringsToNumbersEnabled(bool enable=true); + void setStringsToNumbersEnabled(bool enable = true); bool isStringsToHyperlinksEnabled() const; - void setStringsToHyperlinksEnabled(bool enable=true); + void setStringsToHyperlinksEnabled(bool enable = true); bool isHtmlToRichStringEnabled() const; - void setHtmlToRichStringEnabled(bool enable=true); + void setHtmlToRichStringEnabled(bool enable = true); QString defaultDateFormat() const; void setDefaultDateFormat(const QString &format); - //internal used member - void addMediaFile(QSharedPointer media, bool force=false); - QList > mediaFiles() const; + // internal used member + void addMediaFile(QSharedPointer media, bool force = false); + QList> mediaFiles() const; void addChartFile(QSharedPointer chartFile); - QList > chartFiles() const; + QList> chartFiles() const; private: friend class Worksheet; @@ -104,9 +107,10 @@ private: Theme *theme(); QList images(); QList drawings(); - QList > getSheetsByTypes(AbstractSheet::SheetType type) const; + QList> getSheetsByTypes(AbstractSheet::SheetType type) const; QStringList worksheetNames() const; - AbstractSheet *addSheet(const QString &name, int sheetId, AbstractSheet::SheetType type = AbstractSheet::ST_WorkSheet); + AbstractSheet *addSheet(const QString &name, int sheetId, + AbstractSheet::SheetType type = AbstractSheet::ST_WorkSheet); }; QT_END_NAMESPACE_XLSX diff --git a/src/xlsx/xlsxworkbook_p.h b/src/xlsx/xlsxworkbook_p.h index c3a7c60..6132025 100644 --- a/src/xlsx/xlsxworkbook_p.h +++ b/src/xlsx/xlsxworkbook_p.h @@ -51,17 +51,21 @@ namespace QXlsx { struct XlsxDefineNameData { XlsxDefineNameData() - :sheetId(-1) - {} - XlsxDefineNameData(const QString &name, const QString &formula, const QString &comment, int sheetId=-1) - :name(name), formula(formula), comment(comment), sheetId(sheetId) + : sheetId(-1) + { + } + XlsxDefineNameData(const QString &name, const QString &formula, const QString &comment, + int sheetId = -1) + : name(name) + , formula(formula) + , comment(comment) + , sheetId(sheetId) { - } QString name; QString formula; QString comment; - //using internal sheetId, instead of the localSheetId(order in the workbook) + // using internal sheetId, instead of the localSheetId(order in the workbook) int sheetId; }; @@ -72,13 +76,13 @@ public: WorkbookPrivate(Workbook *q, Workbook::CreateFlag flag); QSharedPointer sharedStrings; - QList > sheets; - QList > externalLinks; + QList> sheets; + QList> externalLinks; QStringList sheetNames; QSharedPointer styles; QSharedPointer theme; - QList > mediaFiles; - QList > chartFiles; + QList> mediaFiles; + QList> chartFiles; QList definedNamesList; bool strings_to_numbers_enabled; @@ -96,12 +100,11 @@ public: int firstsheet; int table_count; - //Used to generate new sheet name and id + // Used to generate new sheet name and id int last_worksheet_index; int last_chartsheet_index; int last_sheet_id; }; - } #endif // XLSXWORKBOOK_P_H diff --git a/src/xlsx/xlsxworksheet.cpp b/src/xlsx/xlsxworksheet.cpp index 8311dd3..7685ca3 100755 --- a/src/xlsx/xlsxworksheet.cpp +++ b/src/xlsx/xlsxworksheet.cpp @@ -61,9 +61,17 @@ QT_BEGIN_NAMESPACE_XLSX WorksheetPrivate::WorksheetPrivate(Worksheet *p, Worksheet::CreateFlag flag) : AbstractSheetPrivate(p, flag) - , windowProtection(false), showFormulas(false), showGridLines(true), showRowColHeaders(true) - , showZeros(true), rightToLeft(false), tabSelected(false), showRuler(false) - , showOutlineSymbols(true), showWhiteSpace(true), urlPattern(QStringLiteral("^([fh]tt?ps?://)|(mailto:)|(file://)")) + , windowProtection(false) + , showFormulas(false) + , showGridLines(true) + , showRowColHeaders(true) + , showZeros(true) + , rightToLeft(false) + , tabSelected(false) + , showRuler(false) + , showOutlineSymbols(true) + , showWhiteSpace(true) + , urlPattern(QStringLiteral("^([fh]tt?ps?://)|(mailto:)|(file://)")) { previous_row = 0; @@ -87,12 +95,13 @@ WorksheetPrivate::~WorksheetPrivate() void WorksheetPrivate::calculateSpans() const { row_spans.clear(); - int span_min = XLSX_COLUMN_MAX+1; + int span_min = XLSX_COLUMN_MAX + 1; int span_max = -1; for (int row_num = dimension.firstRow(); row_num <= dimension.lastRow(); row_num++) { if (cellTable.contains(row_num)) { - for (int col_num = dimension.firstColumn(); col_num <= dimension.lastColumn(); col_num++) { + for (int col_num = dimension.firstColumn(); col_num <= dimension.lastColumn(); + col_num++) { if (cellTable[row_num].contains(col_num)) { if (span_max == -1) { span_min = col_num; @@ -107,7 +116,8 @@ void WorksheetPrivate::calculateSpans() const } } if (comments.contains(row_num)) { - for (int col_num = dimension.firstColumn(); col_num <= dimension.lastColumn(); col_num++) { + for (int col_num = dimension.firstColumn(); col_num <= dimension.lastColumn(); + col_num++) { if (comments[row_num].contains(col_num)) { if (span_max == -1) { span_min = col_num; @@ -122,17 +132,16 @@ void WorksheetPrivate::calculateSpans() const } } - if (row_num%16 == 0 || row_num == dimension.lastRow()) { + if (row_num % 16 == 0 || row_num == dimension.lastRow()) { if (span_max != -1) { row_spans[row_num / 16] = QStringLiteral("%1:%2").arg(span_min).arg(span_max); - span_min = XLSX_COLUMN_MAX+1; + span_min = XLSX_COLUMN_MAX + 1; span_max = -1; } } } } - QString WorksheetPrivate::generateDimensionString() const { if (!dimension.isValid()) @@ -150,19 +159,23 @@ QString WorksheetPrivate::generateDimensionString() const */ int WorksheetPrivate::checkDimensions(int row, int col, bool ignore_row, bool ignore_col) { - Q_ASSERT_X(row!=0, "checkDimensions", "row should start from 1 instead of 0"); - Q_ASSERT_X(col!=0, "checkDimensions", "column should start from 1 instead of 0"); + Q_ASSERT_X(row != 0, "checkDimensions", "row should start from 1 instead of 0"); + Q_ASSERT_X(col != 0, "checkDimensions", "column should start from 1 instead of 0"); if (row > XLSX_ROW_MAX || row < 1 || col > XLSX_COLUMN_MAX || col < 1) return -1; if (!ignore_row) { - if (row < dimension.firstRow() || dimension.firstRow() == -1) dimension.setFirstRow(row); - if (row > dimension.lastRow()) dimension.setLastRow(row); + if (row < dimension.firstRow() || dimension.firstRow() == -1) + dimension.setFirstRow(row); + if (row > dimension.lastRow()) + dimension.setLastRow(row); } if (!ignore_col) { - if (col < dimension.firstColumn() || dimension.firstColumn() == -1) dimension.setFirstColumn(col); - if (col > dimension.lastColumn()) dimension.setLastColumn(col); + if (col < dimension.firstColumn() || dimension.firstColumn() == -1) + dimension.setFirstColumn(col); + if (col > dimension.lastColumn()) + dimension.setLastColumn(col); } return 0; @@ -178,9 +191,9 @@ int WorksheetPrivate::checkDimensions(int row, int col, bool ignore_row, bool ig * \internal */ Worksheet::Worksheet(const QString &name, int id, Workbook *workbook, CreateFlag flag) - :AbstractSheet(name, id, workbook, new WorksheetPrivate(this, flag)) + : AbstractSheet(name, id, workbook, new WorksheetPrivate(this, flag)) { - if (!workbook) //For unit test propose only. Ignore the memery leak. + if (!workbook) // For unit test propose only. Ignore the memery leak. d_func()->workbook = new Workbook(flag); } @@ -198,11 +211,11 @@ Worksheet *Worksheet::copy(const QString &distName, int distId) const sheet_d->dimension = d->dimension; - QMapIterator > > it(d->cellTable); + QMapIterator>> it(d->cellTable); while (it.hasNext()) { it.next(); int row = it.key(); - QMapIterator > it2(it.value()); + QMapIterator> it2(it.value()); while (it2.hasNext()) { it2.next(); int col = it2.key(); @@ -218,11 +231,11 @@ Worksheet *Worksheet::copy(const QString &distName, int distId) const } sheet_d->merges = d->merges; -// sheet_d->rowsInfo = d->rowsInfo; -// sheet_d->colsInfo = d->colsInfo; -// sheet_d->colsInfoHelper = d->colsInfoHelper; -// sheet_d->dataValidationsList = d->dataValidationsList; -// sheet_d->conditionalFormattingList = d->conditionalFormattingList; + // sheet_d->rowsInfo = d->rowsInfo; + // sheet_d->colsInfo = d->colsInfo; + // sheet_d->colsInfoHelper = d->colsInfoHelper; + // sheet_d->dataValidationsList = d->dataValidationsList; + // sheet_d->conditionalFormattingList = d->conditionalFormattingList; return sheet; } @@ -306,7 +319,6 @@ void Worksheet::setRowColumnHeadersVisible(bool visible) d->showRowColHeaders = visible; } - /*! * Return whether the sheet is shown right-to-left or not. */ @@ -368,7 +380,6 @@ bool Worksheet::isRulerVisible() const { Q_D(const Worksheet); return d->showRuler; - } /*! @@ -378,7 +389,6 @@ void Worksheet::setRulerVisible(bool visible) { Q_D(Worksheet); d->showRuler = visible; - } /*! @@ -432,49 +442,50 @@ bool Worksheet::write(int row, int column, const QVariant &value, const Format & bool ret = true; if (value.isNull()) { - //Blank + // Blank ret = writeBlank(row, column, format); } else if (value.userType() == QMetaType::QString) { - //String + // String QString token = value.toString(); bool ok; if (token.startsWith(QLatin1String("="))) { - //convert to formula + // convert to formula ret = writeFormula(row, column, CellFormula(token), format); } else if (d->workbook->isStringsToHyperlinksEnabled() && token.contains(d->urlPattern)) { - //convert to url + // convert to url ret = writeHyperlink(row, column, QUrl(token)); } else if (d->workbook->isStringsToNumbersEnabled() && (value.toDouble(&ok), ok)) { - //Try convert string to number if the flag enabled. + // Try convert string to number if the flag enabled. ret = writeString(row, column, value.toString(), format); } else { - //normal string now + // normal string now ret = writeString(row, column, token, format); } } else if (value.userType() == qMetaTypeId()) { ret = writeString(row, column, value.value(), format); } else if (value.userType() == QMetaType::Int || value.userType() == QMetaType::UInt - || value.userType() == QMetaType::LongLong || value.userType() == QMetaType::ULongLong - || value.userType() == QMetaType::Double || value.userType() == QMetaType::Float) { - //Number + || value.userType() == QMetaType::LongLong + || value.userType() == QMetaType::ULongLong || value.userType() == QMetaType::Double + || value.userType() == QMetaType::Float) { + // Number ret = writeNumeric(row, column, value.toDouble(), format); } else if (value.userType() == QMetaType::Bool) { - //Bool - ret = writeBool(row,column, value.toBool(), format); + // Bool + ret = writeBool(row, column, value.toBool(), format); } else if (value.userType() == QMetaType::QDateTime || value.userType() == QMetaType::QDate) { - //DateTime, Date + // DateTime, Date // note that, QTime cann't convert to QDateTime ret = writeDateTime(row, column, value.toDateTime(), format); } else if (value.userType() == QMetaType::QTime) { - //Time + // Time ret = writeTime(row, column, value.toTime(), format); } else if (value.userType() == QMetaType::QUrl) { - //Url + // Url ret = writeHyperlink(row, column, value.toUrl(), format); } else { - //Wrong type + // Wrong type return false; } @@ -520,16 +531,17 @@ QVariant Worksheet::read(int row, int column) const if (cell->hasFormula()) { if (cell->formula().formulaType() == CellFormula::NormalType) { - return QVariant(QLatin1String("=")+cell->formula().formulaText()); + return QVariant(QLatin1String("=") + cell->formula().formulaText()); } else if (cell->formula().formulaType() == CellFormula::SharedType) { if (!cell->formula().formulaText().isEmpty()) { - return QVariant(QLatin1String("=")+cell->formula().formulaText()); + return QVariant(QLatin1String("=") + cell->formula().formulaText()); } else { const CellFormula &rootFormula = d->sharedFormulaMap[cell->formula().sharedIndex()]; CellReference rootCellRef = rootFormula.reference().topLeft(); QString rootFormulaText = rootFormula.formulaText(); - QString newFormulaText = convertSharedFormula(rootFormulaText, rootCellRef, CellReference(row, column)); - return QVariant(QLatin1String("=")+newFormulaText); + QString newFormulaText = + convertSharedFormula(rootFormulaText, rootCellRef, CellReference(row, column)); + return QVariant(QLatin1String("=") + newFormulaText); } } } @@ -539,7 +551,7 @@ QVariant Worksheet::read(int row, int column) const QDateTime dt = cell->dateTime(); if (val < 1) return dt.time(); - if (fmod(val, 1.0) < 1.0/(1000*60*60*24)) //integer + if (fmod(val, 1.0) < 1.0 / (1000 * 60 * 60 * 24)) // integer return dt.date(); return dt; } @@ -589,7 +601,8 @@ Format WorksheetPrivate::cellFormat(int row, int col) const Returns true on success. */ -bool Worksheet::writeString(const CellReference &row_column, const RichString &value, const Format &format) +bool Worksheet::writeString(const CellReference &row_column, const RichString &value, + const Format &format) { if (!row_column.isValid()) return false; @@ -604,21 +617,22 @@ bool Worksheet::writeString(const CellReference &row_column, const RichString &v bool Worksheet::writeString(int row, int column, const RichString &value, const Format &format) { Q_D(Worksheet); -// QString content = value.toPlainString(); + // QString content = value.toPlainString(); if (d->checkDimensions(row, column)) return false; -// if (content.size() > d->xls_strmax) { -// content = content.left(d->xls_strmax); -// error = -2; -// } + // if (content.size() > d->xls_strmax) { + // content = content.left(d->xls_strmax); + // error = -2; + // } d->sharedStrings()->addSharedString(value); Format fmt = format.isValid() ? format : d->cellFormat(row, column); if (value.fragmentCount() == 1 && value.fragmentFormat(0).isValid()) fmt.mergeFormat(value.fragmentFormat(0)); d->workbook->styles()->addXfFormat(fmt); - QSharedPointer cell = QSharedPointer(new Cell(value.toPlainString(), Cell::SharedStringType, fmt, this)); + QSharedPointer cell = + QSharedPointer(new Cell(value.toPlainString(), Cell::SharedStringType, fmt, this)); cell->d_ptr->richString = value; d->cellTable[row][column] = cell; return true; @@ -628,7 +642,8 @@ bool Worksheet::writeString(int row, int column, const RichString &value, const \overload Write string \a value to the cell \a row_column with the \a format. */ -bool Worksheet::writeString(const CellReference &row_column, const QString &value, const Format &format) +bool Worksheet::writeString(const CellReference &row_column, const QString &value, + const Format &format) { if (!row_column.isValid()) return false; @@ -661,7 +676,8 @@ bool Worksheet::writeString(int row, int column, const QString &value, const For \overload Write string \a value to the cell \a row_column with the \a format */ -bool Worksheet::writeInlineString(const CellReference &row_column, const QString &value, const Format &format) +bool Worksheet::writeInlineString(const CellReference &row_column, const QString &value, + const Format &format) { if (!row_column.isValid()) return false; @@ -676,19 +692,20 @@ bool Worksheet::writeInlineString(const CellReference &row_column, const QString bool Worksheet::writeInlineString(int row, int column, const QString &value, const Format &format) { Q_D(Worksheet); - //int error = 0; + // int error = 0; QString content = value; if (d->checkDimensions(row, column)) return false; if (value.size() > XLSX_STRING_MAX) { content = value.left(XLSX_STRING_MAX); - //error = -2; + // error = -2; } Format fmt = format.isValid() ? format : d->cellFormat(row, column); d->workbook->styles()->addXfFormat(fmt); - d->cellTable[row][column] = QSharedPointer(new Cell(value, Cell::InlineStringType, fmt, this)); + d->cellTable[row][column] = + QSharedPointer(new Cell(value, Cell::InlineStringType, fmt, this)); return true; } @@ -726,7 +743,8 @@ bool Worksheet::writeNumeric(int row, int column, double value, const Format &fo Write \a formula to the cell \a row_column with the \a format and \a result. Returns true on success. */ -bool Worksheet::writeFormula(const CellReference &row_column, const CellFormula &formula, const Format &format, double result) +bool Worksheet::writeFormula(const CellReference &row_column, const CellFormula &formula, + const Format &format, double result) { if (!row_column.isValid()) return false; @@ -738,7 +756,8 @@ bool Worksheet::writeFormula(const CellReference &row_column, const CellFormula Write \a formula_ to the cell (\a row, \a column) with the \a format and \a result. Returns true on success. */ -bool Worksheet::writeFormula(int row, int column, const CellFormula &formula_, const Format &format, double result) +bool Worksheet::writeFormula(int row, int column, const CellFormula &formula_, const Format &format, + double result) { Q_D(Worksheet); if (d->checkDimensions(row, column)) @@ -750,9 +769,9 @@ bool Worksheet::writeFormula(int row, int column, const CellFormula &formula_, c CellFormula formula = formula_; formula.d->ca = true; if (formula.formulaType() == CellFormula::SharedType) { - //Assign proper shared index for shared formula - int si=0; - while(d->sharedFormulaMap.contains(si)) + // Assign proper shared index for shared formula + int si = 0; + while (d->sharedFormulaMap.contains(si)) ++si; formula.d->si = si; d->sharedFormulaMap[si] = formula; @@ -766,13 +785,14 @@ bool Worksheet::writeFormula(int row, int column, const CellFormula &formula_, c if (formula.formulaType() == CellFormula::SharedType) { CellFormula sf(QString(), CellFormula::SharedType); sf.d->si = formula.sharedIndex(); - for (int r=range.firstRow(); r<=range.lastRow(); ++r) { - for (int c=range.firstColumn(); c<=range.lastColumn(); ++c) { - if (!(r==row && c==column)) { - if(Cell *cell = cellAt(r, c)) { + for (int r = range.firstRow(); r <= range.lastRow(); ++r) { + for (int c = range.firstColumn(); c <= range.lastColumn(); ++c) { + if (!(r == row && c == column)) { + if (Cell *cell = cellAt(r, c)) { cell->d_ptr->formula = sf; } else { - QSharedPointer newCell = QSharedPointer(new Cell(result, Cell::NumberType, fmt, this)); + QSharedPointer newCell = + QSharedPointer(new Cell(result, Cell::NumberType, fmt, this)); newCell->d_ptr->formula = sf; d->cellTable[r][c] = newCell; } @@ -780,7 +800,6 @@ bool Worksheet::writeFormula(int row, int column, const CellFormula &formula_, c } } } else if (formula.formulaType() == CellFormula::SharedType) { - } return true; @@ -812,8 +831,9 @@ bool Worksheet::writeBlank(int row, int column, const Format &format) Format fmt = format.isValid() ? format : d->cellFormat(row, column); d->workbook->styles()->addXfFormat(fmt); - //Note: NumberType with an invalid QVariant value means blank. - d->cellTable[row][column] = QSharedPointer(new Cell(QVariant(), Cell::NumberType, fmt, this)); + // Note: NumberType with an invalid QVariant value means blank. + d->cellTable[row][column] = + QSharedPointer(new Cell(QVariant(), Cell::NumberType, fmt, this)); return true; } @@ -851,7 +871,8 @@ bool Worksheet::writeBool(int row, int column, bool value, const Format &format) Write a QDateTime \a dt to the cell \a row_column with the \a format. Returns true on success. */ -bool Worksheet::writeDateTime(const CellReference &row_column, const QDateTime &dt, const Format &format) +bool Worksheet::writeDateTime(const CellReference &row_column, const QDateTime &dt, + const Format &format) { if (!row_column.isValid()) return false; @@ -909,7 +930,8 @@ bool Worksheet::writeTime(int row, int column, const QTime &t, const Format &for fmt.setNumberFormat(QStringLiteral("hh:mm:ss")); d->workbook->styles()->addXfFormat(fmt); - d->cellTable[row][column] = QSharedPointer(new Cell(timeToNumber(t), Cell::NumberType, fmt, this)); + d->cellTable[row][column] = + QSharedPointer(new Cell(timeToNumber(t), Cell::NumberType, fmt, this)); return true; } @@ -919,7 +941,8 @@ bool Worksheet::writeTime(int row, int column, const QTime &t, const Format &for Write a QUrl \a url to the cell \a row_column with the given \a format \a display and \a tip. Returns true on success. */ -bool Worksheet::writeHyperlink(const CellReference &row_column, const QUrl &url, const Format &format, const QString &display, const QString &tip) +bool Worksheet::writeHyperlink(const CellReference &row_column, const QUrl &url, + const Format &format, const QString &display, const QString &tip) { if (!row_column.isValid()) return false; @@ -928,26 +951,27 @@ bool Worksheet::writeHyperlink(const CellReference &row_column, const QUrl &url, } /*! - Write a QUrl \a url to the cell (\a row, \a column) with the given \a format \a display and \a tip. - Returns true on success. + Write a QUrl \a url to the cell (\a row, \a column) with the given \a format \a display and \a + tip. Returns true on success. */ -bool Worksheet::writeHyperlink(int row, int column, const QUrl &url, const Format &format, const QString &display, const QString &tip) +bool Worksheet::writeHyperlink(int row, int column, const QUrl &url, const Format &format, + const QString &display, const QString &tip) { Q_D(Worksheet); if (d->checkDimensions(row, column)) return false; - //int error = 0; + // int error = 0; QString urlString = url.toString(); - //Generate proper display string + // Generate proper display string QString displayString = display.isEmpty() ? urlString : display; if (displayString.startsWith(QLatin1String("mailto:"))) displayString.replace(QLatin1String("mailto:"), QString()); if (displayString.size() > XLSX_STRING_MAX) { displayString = displayString.left(XLSX_STRING_MAX); - //error = -2; + // error = -2; } /* @@ -965,19 +989,21 @@ bool Worksheet::writeHyperlink(int row, int column, const QUrl &url, const Forma } Format fmt = format.isValid() ? format : d->cellFormat(row, column); - //Given a default style for hyperlink + // Given a default style for hyperlink if (!fmt.isValid()) { fmt.setFontColor(Qt::blue); fmt.setFontUnderline(Format::FontUnderlineSingle); } d->workbook->styles()->addXfFormat(fmt); - //Write the hyperlink string as normal string. + // Write the hyperlink string as normal string. d->sharedStrings()->addSharedString(displayString); - d->cellTable[row][column] = QSharedPointer(new Cell(displayString, Cell::SharedStringType, fmt, this)); + d->cellTable[row][column] = + QSharedPointer(new Cell(displayString, Cell::SharedStringType, fmt, this)); - //Store the hyperlink data in a separate table - d->urlTable[row][column] = QSharedPointer(new XlsxHyperlinkData(XlsxHyperlinkData::External, urlString, locationString, QString(), tip)); + // Store the hyperlink data in a separate table + d->urlTable[row][column] = QSharedPointer(new XlsxHyperlinkData( + XlsxHyperlinkData::External, urlString, locationString, QString(), tip)); return true; } @@ -989,7 +1015,7 @@ bool Worksheet::writeHyperlink(int row, int column, const QUrl &url, const Forma bool Worksheet::addDataValidation(const DataValidation &validation) { Q_D(Worksheet); - if (validation.ranges().isEmpty() || validation.validationType()==DataValidation::None) + if (validation.ranges().isEmpty() || validation.validationType() == DataValidation::None) return false; d->dataValidationsList.append(validation); @@ -1006,7 +1032,7 @@ bool Worksheet::addConditionalFormatting(const ConditionalFormatting &cf) if (cf.ranges().isEmpty()) return false; - for (int i=0; icfRules.size(); ++i) { + for (int i = 0; i < cf.d->cfRules.size(); ++i) { const QSharedPointer &rule = cf.d->cfRules[i]; if (!rule->dxfFormat.isEmpty()) d->workbook->styles()->addDxfFormat(rule->dxfFormat); @@ -1030,7 +1056,8 @@ bool Worksheet::insertImage(int row, int column, const QImage &image) if (!d->drawing) d->drawing = QSharedPointer(new Drawing(this, F_NewFromScratch)); - DrawingOneCellAnchor *anchor = new DrawingOneCellAnchor(d->drawing.data(), DrawingAnchor::Picture); + DrawingOneCellAnchor *anchor = + new DrawingOneCellAnchor(d->drawing.data(), DrawingAnchor::Picture); /* The size are expressed as English Metric Units (EMUs). There are @@ -1056,7 +1083,8 @@ Chart *Worksheet::insertChart(int row, int column, const QSize &size) if (!d->drawing) d->drawing = QSharedPointer(new Drawing(this, F_NewFromScratch)); - DrawingOneCellAnchor *anchor = new DrawingOneCellAnchor(d->drawing.data(), DrawingAnchor::Picture); + DrawingOneCellAnchor *anchor = + new DrawingOneCellAnchor(d->drawing.data(), DrawingAnchor::Picture); /* The size are expressed as English Metric Units (EMUs). There are @@ -1146,17 +1174,23 @@ void Worksheet::saveToXmlFile(QIODevice *device) const writer.writeStartDocument(QStringLiteral("1.0"), true); writer.writeStartElement(QStringLiteral("worksheet")); - writer.writeAttribute(QStringLiteral("xmlns"), QStringLiteral("http://schemas.openxmlformats.org/spreadsheetml/2006/main")); - writer.writeAttribute(QStringLiteral("xmlns:r"), QStringLiteral("http://schemas.openxmlformats.org/officeDocument/2006/relationships")); + writer.writeAttribute( + QStringLiteral("xmlns"), + QStringLiteral("http://schemas.openxmlformats.org/spreadsheetml/2006/main")); + writer.writeAttribute( + QStringLiteral("xmlns:r"), + QStringLiteral("http://schemas.openxmlformats.org/officeDocument/2006/relationships")); - //for Excel 2010 - // writer.writeAttribute("xmlns:mc", "http://schemas.openxmlformats.org/markup-compatibility/2006"); - // writer.writeAttribute("xmlns:x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"); + // for Excel 2010 + // writer.writeAttribute("xmlns:mc", + // "http://schemas.openxmlformats.org/markup-compatibility/2006"); + // writer.writeAttribute("xmlns:x14ac", + // "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"); // writer.writeAttribute("mc:Ignorable", "x14ac"); writer.writeStartElement(QStringLiteral("dimension")); writer.writeAttribute(QStringLiteral("ref"), d->generateDimensionString()); - writer.writeEndElement();//dimension + writer.writeEndElement(); // dimension writer.writeStartElement(QStringLiteral("sheetViews")); writer.writeStartElement(QStringLiteral("sheetView")); @@ -1181,26 +1215,29 @@ void Worksheet::saveToXmlFile(QIODevice *device) const if (!d->showWhiteSpace) writer.writeAttribute(QStringLiteral("showWhiteSpace"), QStringLiteral("0")); writer.writeAttribute(QStringLiteral("workbookViewId"), QStringLiteral("0")); - writer.writeEndElement();//sheetView - writer.writeEndElement();//sheetViews + writer.writeEndElement(); // sheetView + writer.writeEndElement(); // sheetViews writer.writeStartElement(QStringLiteral("sheetFormatPr")); - writer.writeAttribute(QStringLiteral("defaultRowHeight"), QString::number(d->default_row_height)); + writer.writeAttribute(QStringLiteral("defaultRowHeight"), + QString::number(d->default_row_height)); if (d->default_row_height != 15) writer.writeAttribute(QStringLiteral("customHeight"), QStringLiteral("1")); if (d->default_row_zeroed) writer.writeAttribute(QStringLiteral("zeroHeight"), QStringLiteral("1")); if (d->outline_row_level) - writer.writeAttribute(QStringLiteral("outlineLevelRow"), QString::number(d->outline_row_level)); + writer.writeAttribute(QStringLiteral("outlineLevelRow"), + QString::number(d->outline_row_level)); if (d->outline_col_level) - writer.writeAttribute(QStringLiteral("outlineLevelCol"), QString::number(d->outline_col_level)); - //for Excel 2010 + writer.writeAttribute(QStringLiteral("outlineLevelCol"), + QString::number(d->outline_col_level)); + // for Excel 2010 // writer.writeAttribute("x14ac:dyDescent", "0.25"); - writer.writeEndElement();//sheetFormatPr + writer.writeEndElement(); // sheetFormatPr if (!d->colsInfo.isEmpty()) { writer.writeStartElement(QStringLiteral("cols")); - QMapIterator > it(d->colsInfo); + QMapIterator> it(d->colsInfo); while (it.hasNext()) { it.next(); QSharedPointer col_info = it.value(); @@ -1208,26 +1245,29 @@ void Worksheet::saveToXmlFile(QIODevice *device) const writer.writeAttribute(QStringLiteral("min"), QString::number(col_info->firstColumn)); writer.writeAttribute(QStringLiteral("max"), QString::number(col_info->lastColumn)); if (col_info->width) - writer.writeAttribute(QStringLiteral("width"), QString::number(col_info->width, 'g', 15)); + writer.writeAttribute(QStringLiteral("width"), + QString::number(col_info->width, 'g', 15)); if (!col_info->format.isEmpty()) - writer.writeAttribute(QStringLiteral("style"), QString::number(col_info->format.xfIndex())); + writer.writeAttribute(QStringLiteral("style"), + QString::number(col_info->format.xfIndex())); if (col_info->hidden) writer.writeAttribute(QStringLiteral("hidden"), QStringLiteral("1")); if (col_info->width) writer.writeAttribute(QStringLiteral("customWidth"), QStringLiteral("1")); if (col_info->outlineLevel) - writer.writeAttribute(QStringLiteral("outlineLevel"), QString::number(col_info->outlineLevel)); + writer.writeAttribute(QStringLiteral("outlineLevel"), + QString::number(col_info->outlineLevel)); if (col_info->collapsed) writer.writeAttribute(QStringLiteral("collapsed"), QStringLiteral("1")); - writer.writeEndElement();//col + writer.writeEndElement(); // col } - writer.writeEndElement();//cols + writer.writeEndElement(); // cols } writer.writeStartElement(QStringLiteral("sheetData")); if (d->dimension.isValid()) d->saveXmlSheetData(writer); - writer.writeEndElement();//sheetData + writer.writeEndElement(); // sheetData d->saveXmlMergeCells(writer); foreach (const ConditionalFormatting cf, d->conditionalFormattingList) @@ -1236,7 +1276,7 @@ void Worksheet::saveToXmlFile(QIODevice *device) const d->saveXmlHyperlinks(writer); d->saveXmlDrawings(writer); - writer.writeEndElement();//worksheet + writer.writeEndElement(); // worksheet writer.writeEndDocument(); } @@ -1244,12 +1284,13 @@ void WorksheetPrivate::saveXmlSheetData(QXmlStreamWriter &writer) const { calculateSpans(); for (int row_num = dimension.firstRow(); row_num <= dimension.lastRow(); row_num++) { - if (!(cellTable.contains(row_num) || comments.contains(row_num) || rowsInfo.contains(row_num))) { - //Only process rows with cell data / comments / formatting + if (!(cellTable.contains(row_num) || comments.contains(row_num) + || rowsInfo.contains(row_num))) { + // Only process rows with cell data / comments / formatting continue; } - int span_index = (row_num-1) / 16; + int span_index = (row_num - 1) / 16; QString span; if (row_spans.contains(span_index)) span = row_spans[span_index]; @@ -1263,11 +1304,12 @@ void WorksheetPrivate::saveXmlSheetData(QXmlStreamWriter &writer) const if (rowsInfo.contains(row_num)) { QSharedPointer rowInfo = rowsInfo[row_num]; if (!rowInfo->format.isEmpty()) { - writer.writeAttribute(QStringLiteral("s"), QString::number(rowInfo->format.xfIndex())); + writer.writeAttribute(QStringLiteral("s"), + QString::number(rowInfo->format.xfIndex())); writer.writeAttribute(QStringLiteral("customFormat"), QStringLiteral("1")); } - //!Todo: support customHeight from info struct - //!Todo: where does this magic number '15' come from? + //! Todo: support customHeight from info struct + //! Todo: where does this magic number '15' come from? if (rowInfo->customHeight) { writer.writeAttribute(QStringLiteral("ht"), QString::number(rowInfo->height)); writer.writeAttribute(QStringLiteral("customHeight"), QStringLiteral("1")); @@ -1278,38 +1320,43 @@ void WorksheetPrivate::saveXmlSheetData(QXmlStreamWriter &writer) const if (rowInfo->hidden) writer.writeAttribute(QStringLiteral("hidden"), QStringLiteral("1")); if (rowInfo->outlineLevel > 0) - writer.writeAttribute(QStringLiteral("outlineLevel"), QString::number(rowInfo->outlineLevel)); + writer.writeAttribute(QStringLiteral("outlineLevel"), + QString::number(rowInfo->outlineLevel)); if (rowInfo->collapsed) writer.writeAttribute(QStringLiteral("collapsed"), QStringLiteral("1")); } - //Write cell data if row contains filled cells + // Write cell data if row contains filled cells if (cellTable.contains(row_num)) { - for (int col_num = dimension.firstColumn(); col_num <= dimension.lastColumn(); col_num++) { + for (int col_num = dimension.firstColumn(); col_num <= dimension.lastColumn(); + col_num++) { if (cellTable[row_num].contains(col_num)) { saveXmlCellData(writer, row_num, col_num, cellTable[row_num][col_num]); } } } - writer.writeEndElement(); //row + writer.writeEndElement(); // row } } -void WorksheetPrivate::saveXmlCellData(QXmlStreamWriter &writer, int row, int col, QSharedPointer cell) const +void WorksheetPrivate::saveXmlCellData(QXmlStreamWriter &writer, int row, int col, + QSharedPointer cell) const { - //This is the innermost loop so efficiency is important. + // This is the innermost loop so efficiency is important. QString cell_pos = CellReference(row, col).toString(); writer.writeStartElement(QStringLiteral("c")); writer.writeAttribute(QStringLiteral("r"), cell_pos); - //Style used by the cell, row or col + // Style used by the cell, row or col if (!cell->format().isEmpty()) writer.writeAttribute(QStringLiteral("s"), QString::number(cell->format().xfIndex())); else if (rowsInfo.contains(row) && !rowsInfo[row]->format.isEmpty()) - writer.writeAttribute(QStringLiteral("s"), QString::number(rowsInfo[row]->format.xfIndex())); + writer.writeAttribute(QStringLiteral("s"), + QString::number(rowsInfo[row]->format.xfIndex())); else if (colsInfoHelper.contains(col) && !colsInfoHelper[col]->format.isEmpty()) - writer.writeAttribute(QStringLiteral("s"), QString::number(colsInfoHelper[col]->format.xfIndex())); + writer.writeAttribute(QStringLiteral("s"), + QString::number(colsInfoHelper[col]->format.xfIndex())); if (cell->cellType() == Cell::SharedStringType) { int sst_idx; @@ -1324,20 +1371,20 @@ void WorksheetPrivate::saveXmlCellData(QXmlStreamWriter &writer, int row, int co writer.writeAttribute(QStringLiteral("t"), QStringLiteral("inlineStr")); writer.writeStartElement(QStringLiteral("is")); if (cell->isRichString()) { - //Rich text string + // Rich text string RichString string = cell->d_ptr->richString; - for (int i=0; icellType() == Cell::NumberType){ + writer.writeEndElement(); // is + } else if (cell->cellType() == Cell::NumberType) { if (cell->hasFormula()) cell->formula().saveToXml(writer); - if (cell->value().isValid()) {//note that, invalid value means 'v' is blank + if (cell->value().isValid()) { // note that, invalid value means 'v' is blank double value = cell->value().toDouble(); writer.writeTextElement(QStringLiteral("v"), QString::number(value, 'g', 15)); } @@ -1363,9 +1410,10 @@ void WorksheetPrivate::saveXmlCellData(QXmlStreamWriter &writer, int row, int co writer.writeTextElement(QStringLiteral("v"), cell->value().toString()); } else if (cell->cellType() == Cell::BooleanType) { writer.writeAttribute(QStringLiteral("t"), QStringLiteral("b")); - writer.writeTextElement(QStringLiteral("v"), cell->value().toBool() ? QStringLiteral("1") : QStringLiteral("0")); + writer.writeTextElement(QStringLiteral("v"), + cell->value().toBool() ? QStringLiteral("1") : QStringLiteral("0")); } - writer.writeEndElement(); //c + writer.writeEndElement(); // c } void WorksheetPrivate::saveXmlMergeCells(QXmlStreamWriter &writer) const @@ -1381,7 +1429,7 @@ void WorksheetPrivate::saveXmlMergeCells(QXmlStreamWriter &writer) const writer.writeAttribute(QStringLiteral("ref"), range.toString()); } - writer.writeEndElement(); //mergeCells + writer.writeEndElement(); // mergeCells } void WorksheetPrivate::saveXmlDataValidations(QXmlStreamWriter &writer) const @@ -1395,7 +1443,7 @@ void WorksheetPrivate::saveXmlDataValidations(QXmlStreamWriter &writer) const foreach (DataValidation validation, dataValidationsList) validation.saveToXml(writer); - writer.writeEndElement(); //dataValidations + writer.writeEndElement(); // dataValidations } void WorksheetPrivate::saveXmlHyperlinks(QXmlStreamWriter &writer) const @@ -1404,11 +1452,11 @@ void WorksheetPrivate::saveXmlHyperlinks(QXmlStreamWriter &writer) const return; writer.writeStartElement(QStringLiteral("hyperlinks")); - QMapIterator > > it(urlTable); + QMapIterator>> it(urlTable); while (it.hasNext()) { it.next(); int row = it.key(); - QMapIterator > it2(it.value()); + QMapIterator> it2(it.value()); while (it2.hasNext()) { it2.next(); int col = it2.key(); @@ -1417,10 +1465,12 @@ void WorksheetPrivate::saveXmlHyperlinks(QXmlStreamWriter &writer) const writer.writeEmptyElement(QStringLiteral("hyperlink")); writer.writeAttribute(QStringLiteral("ref"), ref); if (data->linkType == XlsxHyperlinkData::External) { - //Update relationships - relationships->addWorksheetRelationship(QStringLiteral("/hyperlink"), data->target, QStringLiteral("External")); + // Update relationships + relationships->addWorksheetRelationship(QStringLiteral("/hyperlink"), data->target, + QStringLiteral("External")); - writer.writeAttribute(QStringLiteral("r:id"), QStringLiteral("rId%1").arg(relationships->count())); + writer.writeAttribute(QStringLiteral("r:id"), + QStringLiteral("rId%1").arg(relationships->count())); } if (!data->location.isEmpty()) @@ -1432,7 +1482,7 @@ void WorksheetPrivate::saveXmlHyperlinks(QXmlStreamWriter &writer) const } } - writer.writeEndElement();//hyperlinks + writer.writeEndElement(); // hyperlinks } void WorksheetPrivate::saveXmlDrawings(QXmlStreamWriter &writer) const @@ -1441,10 +1491,12 @@ void WorksheetPrivate::saveXmlDrawings(QXmlStreamWriter &writer) const return; int idx = workbook->drawings().indexOf(drawing.data()); - relationships->addWorksheetRelationship(QStringLiteral("/drawing"), QStringLiteral("../drawings/drawing%1.xml").arg(idx+1)); + relationships->addWorksheetRelationship( + QStringLiteral("/drawing"), QStringLiteral("../drawings/drawing%1.xml").arg(idx + 1)); writer.writeEmptyElement(QStringLiteral("drawing")); - writer.writeAttribute(QStringLiteral("r:id"), QStringLiteral("rId%1").arg(relationships->count())); + writer.writeAttribute(QStringLiteral("r:id"), + QStringLiteral("rId%1").arg(relationships->count())); } void WorksheetPrivate::splitColsInfo(int colFirst, int colLast) @@ -1453,12 +1505,12 @@ void WorksheetPrivate::splitColsInfo(int colFirst, int colLast) // we are trying to set "B:D", there should be "A", "B:D", "E:H". // This will be more complex if we try to set "C:F" after "B:D". { - QMapIterator > it(colsInfo); + QMapIterator> it(colsInfo); while (it.hasNext()) { it.next(); QSharedPointer info = it.value(); if (colFirst > info->firstColumn && colFirst <= info->lastColumn) { - //split the range, + // split the range, QSharedPointer info2(new XlsxColumnInfo(*info)); info->lastColumn = colFirst - 1; info2->firstColumn = colFirst; @@ -1471,7 +1523,7 @@ void WorksheetPrivate::splitColsInfo(int colFirst, int colLast) } } { - QMapIterator > it(colsInfo); + QMapIterator> it(colsInfo); while (it.hasNext()) { it.next(); QSharedPointer info = it.value(); @@ -1540,7 +1592,7 @@ bool Worksheet::setColumnWidth(const CellRange &range, double width) Sets format property of a \a range of columns to \a format. Columns are 1-indexed. Returns true on success. */ -bool Worksheet::setColumnFormat(const CellRange& range, const Format &format) +bool Worksheet::setColumnFormat(const CellRange &range, const Format &format) { if (!range.isValid()) return false; @@ -1570,9 +1622,9 @@ bool Worksheet::setColumnWidth(int colFirst, int colLast, double width) { Q_D(Worksheet); - QList > columnInfoList = d->getColumnInfoList(colFirst, colLast); - foreach(QSharedPointer columnInfo, columnInfoList) - columnInfo->width = width; + QList> columnInfoList = d->getColumnInfoList(colFirst, colLast); + foreach (QSharedPointer columnInfo, columnInfoList) + columnInfo->width = width; return (columnInfoList.count() > 0); } @@ -1586,13 +1638,13 @@ bool Worksheet::setColumnFormat(int colFirst, int colLast, const Format &format) { Q_D(Worksheet); - QList > columnInfoList = d->getColumnInfoList(colFirst, colLast); - foreach(QSharedPointer columnInfo, columnInfoList) - columnInfo->format = format; + QList> columnInfoList = d->getColumnInfoList(colFirst, colLast); + foreach (QSharedPointer columnInfo, columnInfoList) + columnInfo->format = format; - if(columnInfoList.count() > 0) { - d->workbook->styles()->addXfFormat(format); - return true; + if (columnInfoList.count() > 0) { + d->workbook->styles()->addXfFormat(format); + return true; } return false; @@ -1606,9 +1658,9 @@ bool Worksheet::setColumnHidden(int colFirst, int colLast, bool hidden) { Q_D(Worksheet); - QList > columnInfoList = d->getColumnInfoList(colFirst, colLast); - foreach(QSharedPointer columnInfo, columnInfoList) - columnInfo->hidden = hidden; + QList> columnInfoList = d->getColumnInfoList(colFirst, colLast); + foreach (QSharedPointer columnInfo, columnInfoList) + columnInfo->hidden = hidden; return (columnInfoList.count() > 0); } @@ -1620,9 +1672,9 @@ double Worksheet::columnWidth(int column) { Q_D(Worksheet); - QList > columnInfoList = d->getColumnInfoList(column, column); + QList> columnInfoList = d->getColumnInfoList(column, column); if (columnInfoList.count() == 1) - return columnInfoList.at(0)->width ; + return columnInfoList.at(0)->width; return d->sheetFormatProps.defaultColWidth; } @@ -1634,9 +1686,9 @@ Format Worksheet::columnFormat(int column) { Q_D(Worksheet); - QList > columnInfoList = d->getColumnInfoList(column, column); + QList> columnInfoList = d->getColumnInfoList(column, column); if (columnInfoList.count() == 1) - return columnInfoList.at(0)->format; + return columnInfoList.at(0)->format; return Format(); } @@ -1648,9 +1700,9 @@ bool Worksheet::isColumnHidden(int column) { Q_D(Worksheet); - QList > columnInfoList = d->getColumnInfoList(column, column); + QList> columnInfoList = d->getColumnInfoList(column, column); if (columnInfoList.count() == 1) - return columnInfoList.at(0)->hidden; + return columnInfoList.at(0)->hidden; return false; } @@ -1662,13 +1714,13 @@ bool Worksheet::isColumnHidden(int column) Returns true if success. */ -bool Worksheet::setRowHeight(int rowFirst,int rowLast, double height) +bool Worksheet::setRowHeight(int rowFirst, int rowLast, double height) { Q_D(Worksheet); - QList > rowInfoList = d->getRowInfoList(rowFirst,rowLast); + QList> rowInfoList = d->getRowInfoList(rowFirst, rowLast); - foreach(QSharedPointer rowInfo, rowInfoList) { + foreach (QSharedPointer rowInfo, rowInfoList) { rowInfo->height = height; rowInfo->customHeight = true; } @@ -1682,13 +1734,13 @@ bool Worksheet::setRowHeight(int rowFirst,int rowLast, double height) Returns true if success. */ -bool Worksheet::setRowFormat(int rowFirst,int rowLast, const Format &format) +bool Worksheet::setRowFormat(int rowFirst, int rowLast, const Format &format) { Q_D(Worksheet); - QList > rowInfoList = d->getRowInfoList(rowFirst,rowLast); + QList> rowInfoList = d->getRowInfoList(rowFirst, rowLast); - foreach(QSharedPointer rowInfo, rowInfoList) + foreach (QSharedPointer rowInfo, rowInfoList) rowInfo->format = format; d->workbook->styles()->addXfFormat(format); @@ -1701,12 +1753,12 @@ bool Worksheet::setRowFormat(int rowFirst,int rowLast, const Format &format) Returns true if success. */ -bool Worksheet::setRowHidden(int rowFirst,int rowLast, bool hidden) +bool Worksheet::setRowHidden(int rowFirst, int rowLast, bool hidden) { Q_D(Worksheet); - QList > rowInfoList = d->getRowInfoList(rowFirst,rowLast); - foreach(QSharedPointer rowInfo, rowInfoList) + QList> rowInfoList = d->getRowInfoList(rowFirst, rowLast); + foreach (QSharedPointer rowInfo, rowInfoList) rowInfo->hidden = hidden; return rowInfoList.count() > 0; @@ -1721,8 +1773,7 @@ double Worksheet::rowHeight(int row) int min_col = d->dimension.isValid() ? d->dimension.firstColumn() : 1; if (d->checkDimensions(row, min_col, false, true) || !d->rowsInfo.contains(row)) - return d->sheetFormatProps.defaultRowHeight; //return default on invalid row - + return d->sheetFormatProps.defaultRowHeight; // return default on invalid row return d->rowsInfo[row]->height; } @@ -1735,7 +1786,7 @@ Format Worksheet::rowFormat(int row) Q_D(Worksheet); int min_col = d->dimension.isValid() ? d->dimension.firstColumn() : 1; if (d->checkDimensions(row, min_col, false, true) || !d->rowsInfo.contains(row)) - return Format(); //return default on invalid row + return Format(); // return default on invalid row return d->rowsInfo[row]->format; } @@ -1748,7 +1799,7 @@ bool Worksheet::isRowHidden(int row) Q_D(Worksheet); int min_col = d->dimension.isValid() ? d->dimension.firstColumn() : 1; if (d->checkDimensions(row, min_col, false, true) || !d->rowsInfo.contains(row)) - return false; //return default on invalid row + return false; // return default on invalid row return d->rowsInfo[row]->hidden; } @@ -1762,7 +1813,7 @@ bool Worksheet::groupRows(int rowFirst, int rowLast, bool collapsed) { Q_D(Worksheet); - for (int row=rowFirst; row<=rowLast; ++row) { + for (int row = rowFirst; row <= rowLast; ++row) { if (d->rowsInfo.contains(row)) { d->rowsInfo[row]->outlineLevel += 1; } else { @@ -1774,9 +1825,9 @@ bool Worksheet::groupRows(int rowFirst, int rowLast, bool collapsed) d->rowsInfo[row]->hidden = true; } if (collapsed) { - if (!d->rowsInfo.contains(rowLast+1)) - d->rowsInfo.insert(rowLast+1, QSharedPointer(new XlsxRowInfo)); - d->rowsInfo[rowLast+1]->collapsed = true; + if (!d->rowsInfo.contains(rowLast + 1)) + d->rowsInfo.insert(rowLast + 1, QSharedPointer(new XlsxRowInfo)); + d->rowsInfo[rowLast + 1]->collapsed = true; } return true; } @@ -1824,7 +1875,7 @@ bool Worksheet::groupColumns(int colFirst, int colLast, bool collapsed) if (collapsed) info->hidden = true; } else { - int colEnd = (idx == nodes.size() - 1) ? colLast : nodes[idx+1] - 1; + int colEnd = (idx == nodes.size() - 1) ? colLast : nodes[idx + 1] - 1; QSharedPointer info(new XlsxColumnInfo(colStart, colEnd)); info->outlineLevel += 1; d->colsInfo.insert(colFirst, info); @@ -1836,7 +1887,7 @@ bool Worksheet::groupColumns(int colFirst, int colLast, bool collapsed) } if (collapsed) { - int col = colLast+1; + int col = colLast + 1; d->splitColsInfo(col, col); if (d->colsInfo.contains(col)) d->colsInfo[col]->collapsed = true; @@ -1872,7 +1923,7 @@ int WorksheetPrivate::rowPixelsSize(int row) const height = row_sizes[row]; else height = default_row_height; - return static_cast(4.0 / 3.0 *height); + return static_cast(4.0 / 3.0 * height); } /* @@ -1883,7 +1934,7 @@ int WorksheetPrivate::rowPixelsSize(int row) const */ int WorksheetPrivate::colPixelsSize(int col) const { - double max_digit_width = 7.0; //For Calabri 11 + double max_digit_width = 7.0; // For Calabri 11 double padding = 5.0; int pixels = 0; @@ -1904,37 +1955,44 @@ void WorksheetPrivate::loadXmlSheetData(QXmlStreamReader &reader) Q_Q(Worksheet); Q_ASSERT(reader.name() == QLatin1String("sheetData")); - while (!reader.atEnd() && !(reader.name() == QLatin1String("sheetData") && reader.tokenType() == QXmlStreamReader::EndElement)) { + while (!reader.atEnd() + && !(reader.name() == QLatin1String("sheetData") + && reader.tokenType() == QXmlStreamReader::EndElement)) { if (reader.readNextStartElement()) { if (reader.name() == QLatin1String("row")) { QXmlStreamAttributes attributes = reader.attributes(); if (attributes.hasAttribute(QLatin1String("customFormat")) - || attributes.hasAttribute(QLatin1String("customHeight")) - || attributes.hasAttribute(QLatin1String("hidden")) - || attributes.hasAttribute(QLatin1String("outlineLevel")) - || attributes.hasAttribute(QLatin1String("collapsed"))) { + || attributes.hasAttribute(QLatin1String("customHeight")) + || attributes.hasAttribute(QLatin1String("hidden")) + || attributes.hasAttribute(QLatin1String("outlineLevel")) + || attributes.hasAttribute(QLatin1String("collapsed"))) { QSharedPointer info(new XlsxRowInfo); - if (attributes.hasAttribute(QLatin1String("customFormat")) && attributes.hasAttribute(QLatin1String("s"))) { + if (attributes.hasAttribute(QLatin1String("customFormat")) + && attributes.hasAttribute(QLatin1String("s"))) { int idx = attributes.value(QLatin1String("s")).toString().toInt(); info->format = workbook->styles()->xfFormat(idx); } if (attributes.hasAttribute(QLatin1String("customHeight"))) { - info->customHeight = attributes.value(QLatin1String("customHeight")) == QLatin1String("1"); - //Row height is only specified when customHeight is set - if(attributes.hasAttribute(QLatin1String("ht"))) { - info->height = attributes.value(QLatin1String("ht")).toString().toDouble(); + info->customHeight = + attributes.value(QLatin1String("customHeight")) == QLatin1String("1"); + // Row height is only specified when customHeight is set + if (attributes.hasAttribute(QLatin1String("ht"))) { + info->height = + attributes.value(QLatin1String("ht")).toString().toDouble(); } } - //both "hidden" and "collapsed" default are false + // both "hidden" and "collapsed" default are false info->hidden = attributes.value(QLatin1String("hidden")) == QLatin1String("1"); - info->collapsed = attributes.value(QLatin1String("collapsed")) == QLatin1String("1"); + info->collapsed = + attributes.value(QLatin1String("collapsed")) == QLatin1String("1"); if (attributes.hasAttribute(QLatin1String("outlineLevel"))) - info->outlineLevel = attributes.value(QLatin1String("outlineLevel")).toString().toInt(); + info->outlineLevel = + attributes.value(QLatin1String("outlineLevel")).toString().toInt(); //"r" is optional too. if (attributes.hasAttribute(QLatin1String("r"))) { @@ -1943,19 +2001,20 @@ void WorksheetPrivate::loadXmlSheetData(QXmlStreamReader &reader) } } - } else if (reader.name() == QLatin1String("c")) { //Cell + } else if (reader.name() == QLatin1String("c")) { // Cell QXmlStreamAttributes attributes = reader.attributes(); QString r = attributes.value(QLatin1String("r")).toString(); CellReference pos(r); - //get format + // get format Format format; if (attributes.hasAttribute(QLatin1String("s"))) { //"s" == style index int idx = attributes.value(QLatin1String("s")).toString().toInt(); format = workbook->styles()->xfFormat(idx); ////Empty format exists in styles xf table of real .xlsx files, see issue #65. - //if (!format.isValid()) - // qDebug()<Invalid style index: ").arg(idx)<Invalid style index: + // ").arg(idx)< cell(new Cell(QVariant() ,cellType, format, q)); - while (!reader.atEnd() && !(reader.name() == QLatin1String("c") && reader.tokenType() == QXmlStreamReader::EndElement)) { + QSharedPointer cell(new Cell(QVariant(), cellType, format, q)); + while (!reader.atEnd() + && !(reader.name() == QLatin1String("c") + && reader.tokenType() == QXmlStreamReader::EndElement)) { if (reader.readNextStartElement()) { if (reader.name() == QLatin1String("f")) { CellFormula &formula = cell->d_func()->formula; formula.loadFromXml(reader); - if (formula.formulaType() == CellFormula::SharedType && !formula.formulaText().isEmpty()) { + if (formula.formulaType() == CellFormula::SharedType + && !formula.formulaText().isEmpty()) { sharedFormulaMap[formula.sharedIndex()] = formula; } } else if (reader.name() == QLatin1String("v")) { @@ -1997,11 +2059,13 @@ void WorksheetPrivate::loadXmlSheetData(QXmlStreamReader &reader) cell->d_func()->value = value.toDouble(); } else if (cellType == Cell::BooleanType) { cell->d_func()->value = value.toInt() ? true : false; - } else { //Cell::ErrorType and Cell::StringType + } else { // Cell::ErrorType and Cell::StringType cell->d_func()->value = value; } } else if (reader.name() == QLatin1String("is")) { - while (!reader.atEnd() && !(reader.name() == QLatin1String("is") && reader.tokenType() == QXmlStreamReader::EndElement)) { + while (!reader.atEnd() + && !(reader.name() == QLatin1String("is") + && reader.tokenType() == QXmlStreamReader::EndElement)) { if (reader.readNextStartElement()) { //:Todo, add rich text read support if (reader.name() == QLatin1String("t")) { @@ -2010,9 +2074,10 @@ void WorksheetPrivate::loadXmlSheetData(QXmlStreamReader &reader) } } } else if (reader.name() == QLatin1String("extLst")) { - //skip extLst element - while (!reader.atEnd() && !(reader.name() == QLatin1String("extLst") - && reader.tokenType() == QXmlStreamReader::EndElement)) { + // skip extLst element + while (!reader.atEnd() + && !(reader.name() == QLatin1String("extLst") + && reader.tokenType() == QXmlStreamReader::EndElement)) { reader.readNextStartElement(); } } @@ -2028,7 +2093,9 @@ void WorksheetPrivate::loadXmlColumnsInfo(QXmlStreamReader &reader) { Q_ASSERT(reader.name() == QLatin1String("cols")); - while (!reader.atEnd() && !(reader.name() == QLatin1String("cols") && reader.tokenType() == QXmlStreamReader::EndElement)) { + while (!reader.atEnd() + && !(reader.name() == QLatin1String("cols") + && reader.tokenType() == QXmlStreamReader::EndElement)) { reader.readNextStartElement(); if (reader.tokenType() == QXmlStreamReader::StartElement) { if (reader.name() == QLatin1String("col")) { @@ -2040,12 +2107,14 @@ void WorksheetPrivate::loadXmlColumnsInfo(QXmlStreamReader &reader) info->firstColumn = min; info->lastColumn = max; - //Flag indicating that the column width for the affected column(s) is different from the + // Flag indicating that the column width for the affected column(s) is different + // from the // default or has been manually set - if(colAttrs.hasAttribute(QLatin1String("customWidth"))) { - info->customWidth = colAttrs.value(QLatin1String("customWidth")) == QLatin1String("1"); + if (colAttrs.hasAttribute(QLatin1String("customWidth"))) { + info->customWidth = + colAttrs.value(QLatin1String("customWidth")) == QLatin1String("1"); } - //Note, node may have "width" without "customWidth" + // Note, node may have "width" without "customWidth" if (colAttrs.hasAttribute(QLatin1String("width"))) { double width = colAttrs.value(QLatin1String("width")).toString().toDouble(); info->width = width; @@ -2059,10 +2128,11 @@ void WorksheetPrivate::loadXmlColumnsInfo(QXmlStreamReader &reader) info->format = workbook->styles()->xfFormat(idx); } if (colAttrs.hasAttribute(QLatin1String("outlineLevel"))) - info->outlineLevel = colAttrs.value(QLatin1String("outlineLevel")).toString().toInt(); + info->outlineLevel = + colAttrs.value(QLatin1String("outlineLevel")).toString().toInt(); colsInfo.insert(min, info); - for (int col=min; col<=max; ++col) + for (int col = min; col <= max; ++col) colsInfoHelper[col] = info; } } @@ -2076,7 +2146,9 @@ void WorksheetPrivate::loadXmlMergeCells(QXmlStreamReader &reader) QXmlStreamAttributes attributes = reader.attributes(); int count = attributes.value(QLatin1String("count")).toString().toInt(); - while (!reader.atEnd() && !(reader.name() == QLatin1String("mergeCells") && reader.tokenType() == QXmlStreamReader::EndElement)) { + while (!reader.atEnd() + && !(reader.name() == QLatin1String("mergeCells") + && reader.tokenType() == QXmlStreamReader::EndElement)) { reader.readNextStartElement(); if (reader.tokenType() == QXmlStreamReader::StartElement) { if (reader.name() == QLatin1String("mergeCell")) { @@ -2097,11 +2169,12 @@ void WorksheetPrivate::loadXmlDataValidations(QXmlStreamReader &reader) QXmlStreamAttributes attributes = reader.attributes(); int count = attributes.value(QLatin1String("count")).toString().toInt(); - while (!reader.atEnd() && !(reader.name() == QLatin1String("dataValidations") - && reader.tokenType() == QXmlStreamReader::EndElement)) { + while (!reader.atEnd() + && !(reader.name() == QLatin1String("dataValidations") + && reader.tokenType() == QXmlStreamReader::EndElement)) { reader.readNextStartElement(); if (reader.tokenType() == QXmlStreamReader::StartElement - && reader.name() == QLatin1String("dataValidation")) { + && reader.name() == QLatin1String("dataValidation")) { dataValidationsList.append(DataValidation::loadFromXml(reader)); } } @@ -2114,22 +2187,26 @@ void WorksheetPrivate::loadXmlSheetViews(QXmlStreamReader &reader) { Q_ASSERT(reader.name() == QLatin1String("sheetViews")); - while (!reader.atEnd() && !(reader.name() == QLatin1String("sheetViews") - && reader.tokenType() == QXmlStreamReader::EndElement)) { + while (!reader.atEnd() + && !(reader.name() == QLatin1String("sheetViews") + && reader.tokenType() == QXmlStreamReader::EndElement)) { reader.readNextStartElement(); - if (reader.tokenType() == QXmlStreamReader::StartElement && reader.name() == QLatin1String("sheetView")) { + if (reader.tokenType() == QXmlStreamReader::StartElement + && reader.name() == QLatin1String("sheetView")) { QXmlStreamAttributes attrs = reader.attributes(); - //default false + // default false windowProtection = attrs.value(QLatin1String("windowProtection")) == QLatin1String("1"); showFormulas = attrs.value(QLatin1String("showFormulas")) == QLatin1String("1"); rightToLeft = attrs.value(QLatin1String("rightToLeft")) == QLatin1String("1"); tabSelected = attrs.value(QLatin1String("tabSelected")) == QLatin1String("1"); - //default true + // default true showGridLines = attrs.value(QLatin1String("showGridLines")) != QLatin1String("0"); - showRowColHeaders = attrs.value(QLatin1String("showRowColHeaders")) != QLatin1String("0"); + showRowColHeaders = + attrs.value(QLatin1String("showRowColHeaders")) != QLatin1String("0"); showZeros = attrs.value(QLatin1String("showZeros")) != QLatin1String("0"); showRuler = attrs.value(QLatin1String("showRuler")) != QLatin1String("0"); - showOutlineSymbols = attrs.value(QLatin1String("showOutlineSymbols")) != QLatin1String("0"); + showOutlineSymbols = + attrs.value(QLatin1String("showOutlineSymbols")) != QLatin1String("0"); showWhiteSpace = attrs.value(QLatin1String("showWhiteSpace")) != QLatin1String("0"); } } @@ -2141,38 +2218,37 @@ void WorksheetPrivate::loadXmlSheetFormatProps(QXmlStreamReader &reader) QXmlStreamAttributes attributes = reader.attributes(); XlsxSheetFormatProps formatProps; - //Retain default values + // Retain default values foreach (QXmlStreamAttribute attrib, attributes) { - if(attrib.name() == QLatin1String("baseColWidth") ) { + if (attrib.name() == QLatin1String("baseColWidth")) { formatProps.baseColWidth = attrib.value().toString().toInt(); - } else if(attrib.name() == QLatin1String("customHeight")) { + } else if (attrib.name() == QLatin1String("customHeight")) { formatProps.customHeight = attrib.value() == QLatin1String("1"); - } else if(attrib.name() == QLatin1String("defaultColWidth")) { + } else if (attrib.name() == QLatin1String("defaultColWidth")) { formatProps.defaultColWidth = attrib.value().toString().toDouble(); - } else if(attrib.name() == QLatin1String("defaultRowHeight")) { + } else if (attrib.name() == QLatin1String("defaultRowHeight")) { formatProps.defaultRowHeight = attrib.value().toString().toDouble(); - } else if(attrib.name() == QLatin1String("outlineLevelCol")) { + } else if (attrib.name() == QLatin1String("outlineLevelCol")) { formatProps.outlineLevelCol = attrib.value().toString().toInt(); - } else if(attrib.name() == QLatin1String("outlineLevelRow")) { + } else if (attrib.name() == QLatin1String("outlineLevelRow")) { formatProps.outlineLevelRow = attrib.value().toString().toInt(); - } else if(attrib.name() == QLatin1String("thickBottom")) { + } else if (attrib.name() == QLatin1String("thickBottom")) { formatProps.thickBottom = attrib.value() == QLatin1String("1"); - } else if(attrib.name() == QLatin1String("thickTop")) { - formatProps.thickTop = attrib.value() == QLatin1String("1"); - } else if(attrib.name() == QLatin1String("zeroHeight")) { + } else if (attrib.name() == QLatin1String("thickTop")) { + formatProps.thickTop = attrib.value() == QLatin1String("1"); + } else if (attrib.name() == QLatin1String("zeroHeight")) { formatProps.zeroHeight = attrib.value() == QLatin1String("1"); } } - if(formatProps.defaultColWidth == 0.0) { //not set - formatProps.defaultColWidth = WorksheetPrivate::calculateColWidth(formatProps.baseColWidth); + if (formatProps.defaultColWidth == 0.0) { // not set + formatProps.defaultColWidth = WorksheetPrivate::calculateColWidth(formatProps.baseColWidth); } - } double WorksheetPrivate::calculateColWidth(int characters) { - //!Todo - //Take normal style' font maximum width and add padding and margin pixels + //! Todo + // Take normal style' font maximum width and add padding and margin pixels return characters + 0.5; } @@ -2180,13 +2256,15 @@ void WorksheetPrivate::loadXmlHyperlinks(QXmlStreamReader &reader) { Q_ASSERT(reader.name() == QLatin1String("hyperlinks")); - while (!reader.atEnd() && !(reader.name() == QLatin1String("hyperlinks") - && reader.tokenType() == QXmlStreamReader::EndElement)) { + while (!reader.atEnd() + && !(reader.name() == QLatin1String("hyperlinks") + && reader.tokenType() == QXmlStreamReader::EndElement)) { reader.readNextStartElement(); - if (reader.tokenType() == QXmlStreamReader::StartElement && reader.name() == QLatin1String("hyperlink")) { + if (reader.tokenType() == QXmlStreamReader::StartElement + && reader.name() == QLatin1String("hyperlink")) { QXmlStreamAttributes attrs = reader.attributes(); CellReference pos(attrs.value(QLatin1String("ref")).toString()); - if (pos.isValid()) { //Valid + if (pos.isValid()) { // Valid QSharedPointer link(new XlsxHyperlinkData); link->display = attrs.value(QLatin1String("display")).toString(); link->tooltip = attrs.value(QLatin1String("tooltip")).toString(); @@ -2194,7 +2272,8 @@ void WorksheetPrivate::loadXmlHyperlinks(QXmlStreamReader &reader) if (attrs.hasAttribute(QLatin1String("r:id"))) { link->linkType = XlsxHyperlinkData::External; - XlsxRelationship ship = relationships->getRelationshipById(attrs.value(QLatin1String("r:id")).toString()); + XlsxRelationship ship = relationships->getRelationshipById( + attrs.value(QLatin1String("r:id")).toString()); link->target = ship.target; } else { link->linkType = XlsxHyperlinkData::Internal; @@ -2206,11 +2285,10 @@ void WorksheetPrivate::loadXmlHyperlinks(QXmlStreamReader &reader) } } -QList > WorksheetPrivate::getColumnInfoList(int colFirst, int colLast) +QList> WorksheetPrivate::getColumnInfoList(int colFirst, int colLast) { - QList > columnsInfoList; - if(isColumnRangeValid(colFirst,colLast)) - { + QList> columnsInfoList; + if (isColumnRangeValid(colFirst, colLast)) { QList nodes = getColumnIndexes(colFirst, colLast); for (int idx = 0; idx < nodes.size(); ++idx) { @@ -2219,7 +2297,7 @@ QList > WorksheetPrivate::getColumnInfoList(int QSharedPointer info = colsInfo[colStart]; columnsInfoList.append(info); } else { - int colEnd = (idx == nodes.size() - 1) ? colLast : nodes[idx+1] - 1; + int colEnd = (idx == nodes.size() - 1) ? colLast : nodes[idx + 1] - 1; QSharedPointer info(new XlsxColumnInfo(colStart, colEnd)); colsInfo.insert(colFirst, info); columnsInfoList.append(info); @@ -2232,18 +2310,18 @@ QList > WorksheetPrivate::getColumnInfoList(int return columnsInfoList; } -QList > WorksheetPrivate::getRowInfoList(int rowFirst, int rowLast) +QList> WorksheetPrivate::getRowInfoList(int rowFirst, int rowLast) { - QList > rowInfoList; + QList> rowInfoList; int min_col = dimension.firstColumn() < 1 ? 1 : dimension.firstColumn(); - for(int row = rowFirst; row <= rowLast; ++row) { + for (int row = rowFirst; row <= rowLast; ++row) { if (checkDimensions(row, min_col, false, true)) continue; QSharedPointer rowInfo; - if ((rowsInfo[row]).isNull()){ + if ((rowsInfo[row]).isNull()) { rowsInfo[row] = QSharedPointer(new XlsxRowInfo()); } rowInfoList.append(rowsInfo[row]); @@ -2285,13 +2363,15 @@ bool Worksheet::loadFromXmlFile(QIODevice *device) } else if (reader.name() == QLatin1String("drawing")) { QString rId = reader.attributes().value(QStringLiteral("r:id")).toString(); QString name = d->relationships->getRelationshipById(rId).target; - QString path = QDir::cleanPath(splitPath(filePath())[0] + QLatin1String("/") + name); + QString path = + QDir::cleanPath(splitPath(filePath())[0] + QLatin1String("/") + name); d->drawing = QSharedPointer(new Drawing(this, F_LoadFromExists)); d->drawing->setFilePath(path); } else if (reader.name() == QLatin1String("extLst")) { - //Todo: add extLst support - while (!reader.atEnd() && !(reader.name() == QLatin1String("extLst") - && reader.tokenType() == QXmlStreamReader::EndElement)) { + // Todo: add extLst support + while (!reader.atEnd() + && !(reader.name() == QLatin1String("extLst") + && reader.tokenType() == QXmlStreamReader::EndElement)) { reader.readNextStartElement(); } } @@ -2311,19 +2391,19 @@ void WorksheetPrivate::validateDimension() return; int firstRow = cellTable.constBegin().key(); - int lastRow = (cellTable.constEnd()-1).key(); + int lastRow = (cellTable.constEnd() - 1).key(); int firstColumn = -1; int lastColumn = -1; - for (QMap > >::const_iterator it = cellTable.begin(); it != cellTable.end(); ++it) - { + for (QMap>>::const_iterator it = cellTable.begin(); + it != cellTable.end(); ++it) { Q_ASSERT(!it.value().isEmpty()); if (firstColumn == -1 || it.value().constBegin().key() < firstColumn) firstColumn = it.value().constBegin().key(); - if (lastColumn == -1 || (it.value().constEnd()-1).key() > lastColumn) - lastColumn = (it.value().constEnd()-1).key(); + if (lastColumn == -1 || (it.value().constEnd() - 1).key() > lastColumn) + lastColumn = (it.value().constEnd() - 1).key(); } CellRange cr(firstRow, firstColumn, lastRow, lastColumn); diff --git a/src/xlsx/xlsxworksheet.h b/src/xlsx/xlsxworksheet.h index 6883370..847febe 100755 --- a/src/xlsx/xlsxworksheet.h +++ b/src/xlsx/xlsxworksheet.h @@ -57,31 +57,44 @@ class Q_XLSX_EXPORT Worksheet : public AbstractSheet { Q_DECLARE_PRIVATE(Worksheet) public: - bool write(const CellReference &row_column, const QVariant &value, const Format &format=Format()); - bool write(int row, int column, const QVariant &value, const Format &format=Format()); + bool write(const CellReference &row_column, const QVariant &value, + const Format &format = Format()); + bool write(int row, int column, const QVariant &value, const Format &format = Format()); QVariant read(const CellReference &row_column) const; QVariant read(int row, int column) const; - bool writeString(const CellReference &row_column, const QString &value, const Format &format=Format()); - bool writeString(int row, int column, const QString &value, const Format &format=Format()); - bool writeString(const CellReference &row_column, const RichString &value, const Format &format=Format()); - bool writeString(int row, int column, const RichString &value, const Format &format=Format()); - bool writeInlineString(const CellReference &row_column, const QString &value, const Format &format=Format()); - bool writeInlineString(int row, int column, const QString &value, const Format &format=Format()); - bool writeNumeric(const CellReference &row_column, double value, const Format &format=Format()); - bool writeNumeric(int row, int column, double value, const Format &format=Format()); - bool writeFormula(const CellReference &row_column, const CellFormula &formula, const Format &format=Format(), double result=0); - bool writeFormula(int row, int column, const CellFormula &formula, const Format &format=Format(), double result=0); - bool writeBlank(const CellReference &row_column, const Format &format=Format()); - bool writeBlank(int row, int column, const Format &format=Format()); - bool writeBool(const CellReference &row_column, bool value, const Format &format=Format()); - bool writeBool(int row, int column, bool value, const Format &format=Format()); - bool writeDateTime(const CellReference &row_column, const QDateTime& dt, const Format &format=Format()); - bool writeDateTime(int row, int column, const QDateTime& dt, const Format &format=Format()); - bool writeTime(const CellReference &row_column, const QTime& t, const Format &format=Format()); - bool writeTime(int row, int column, const QTime& t, const Format &format=Format()); + bool writeString(const CellReference &row_column, const QString &value, + const Format &format = Format()); + bool writeString(int row, int column, const QString &value, const Format &format = Format()); + bool writeString(const CellReference &row_column, const RichString &value, + const Format &format = Format()); + bool writeString(int row, int column, const RichString &value, const Format &format = Format()); + bool writeInlineString(const CellReference &row_column, const QString &value, + const Format &format = Format()); + bool writeInlineString(int row, int column, const QString &value, + const Format &format = Format()); + bool writeNumeric(const CellReference &row_column, double value, + const Format &format = Format()); + bool writeNumeric(int row, int column, double value, const Format &format = Format()); + bool writeFormula(const CellReference &row_column, const CellFormula &formula, + const Format &format = Format(), double result = 0); + bool writeFormula(int row, int column, const CellFormula &formula, + const Format &format = Format(), double result = 0); + bool writeBlank(const CellReference &row_column, const Format &format = Format()); + bool writeBlank(int row, int column, const Format &format = Format()); + bool writeBool(const CellReference &row_column, bool value, const Format &format = Format()); + bool writeBool(int row, int column, bool value, const Format &format = Format()); + bool writeDateTime(const CellReference &row_column, const QDateTime &dt, + const Format &format = Format()); + bool writeDateTime(int row, int column, const QDateTime &dt, const Format &format = Format()); + bool writeTime(const CellReference &row_column, const QTime &t, + const Format &format = Format()); + bool writeTime(int row, int column, const QTime &t, const Format &format = Format()); - bool writeHyperlink(const CellReference &row_column, const QUrl &url, const Format &format=Format(), const QString &display=QString(), const QString &tip=QString()); - bool writeHyperlink(int row, int column, const QUrl &url, const Format &format=Format(), const QString &display=QString(), const QString &tip=QString()); + bool writeHyperlink(const CellReference &row_column, const QUrl &url, + const Format &format = Format(), const QString &display = QString(), + const QString &tip = QString()); + bool writeHyperlink(int row, int column, const QUrl &url, const Format &format = Format(), + const QString &display = QString(), const QString &tip = QString()); bool addDataValidation(const DataValidation &validation); bool addConditionalFormatting(const ConditionalFormatting &cf); @@ -92,13 +105,13 @@ public: bool insertImage(int row, int column, const QImage &image); Chart *insertChart(int row, int column, const QSize &size); - bool mergeCells(const CellRange &range, const Format &format=Format()); + bool mergeCells(const CellRange &range, const Format &format = Format()); bool unmergeCells(const CellRange &range); QList mergedCells() const; - bool setColumnWidth(const CellRange& range, double width); - bool setColumnFormat(const CellRange& range, const Format &format); - bool setColumnHidden(const CellRange& range, bool hidden); + bool setColumnWidth(const CellRange &range, double width); + bool setColumnFormat(const CellRange &range, const Format &format); + bool setColumnHidden(const CellRange &range, bool hidden); bool setColumnWidth(int colFirst, int colLast, double width); bool setColumnFormat(int colFirst, int colLast, const Format &format); bool setColumnHidden(int colFirst, int colLast, bool hidden); @@ -106,9 +119,9 @@ public: Format columnFormat(int column); bool isColumnHidden(int column); - bool setRowHeight(int rowFirst,int rowLast, double height); - bool setRowFormat(int rowFirst,int rowLast, const Format &format); - bool setRowHidden(int rowFirst,int rowLast, bool hidden); + bool setRowHeight(int rowFirst, int rowLast, double height); + bool setRowFormat(int rowFirst, int rowLast, const Format &format); + bool setRowHidden(int rowFirst, int rowLast, bool hidden); double rowHeight(int row); Format rowFormat(int row); @@ -142,7 +155,6 @@ public: ~Worksheet(); - private: friend class DocumentPrivate; friend class Workbook; diff --git a/src/xlsx/xlsxworksheet_p.h b/src/xlsx/xlsxworksheet_p.h index b3f5849..3fa377f 100644 --- a/src/xlsx/xlsxworksheet_p.h +++ b/src/xlsx/xlsxworksheet_p.h @@ -60,21 +60,21 @@ class SharedStrings; struct XlsxHyperlinkData { - enum LinkType - { - External, - Internal - }; + enum LinkType { External, Internal }; - XlsxHyperlinkData(LinkType linkType=External, const QString &target=QString(), const QString &location=QString() - , const QString &display=QString(), const QString &tip=QString()) - :linkType(linkType), target(target), location(location), display(display), tooltip(tip) + XlsxHyperlinkData(LinkType linkType = External, const QString &target = QString(), + const QString &location = QString(), const QString &display = QString(), + const QString &tip = QString()) + : linkType(linkType) + , target(target) + , location(location) + , display(display) + , tooltip(tip) { - } LinkType linkType; - QString target; //For External link + QString target; // For External link QString location; QString display; QString tooltip; @@ -83,24 +83,20 @@ struct XlsxHyperlinkData // ECMA-376 Part1 18.3.1.81 struct XlsxSheetFormatProps { - XlsxSheetFormatProps(int baseColWidth = 8, - bool customHeight = false, - double defaultColWidth = 0.0, - double defaultRowHeight = 15, - quint8 outlineLevelCol = 0, - quint8 outlineLevelRow = 0, - bool thickBottom = false, - bool thickTop = false, - bool zeroHeight = false) : - baseColWidth(baseColWidth), - customHeight(customHeight), - defaultColWidth(defaultColWidth), - defaultRowHeight(defaultRowHeight), - outlineLevelCol(outlineLevelCol), - outlineLevelRow(outlineLevelRow), - thickBottom(thickBottom), - thickTop(thickTop), - zeroHeight(zeroHeight) { + XlsxSheetFormatProps(int baseColWidth = 8, bool customHeight = false, + double defaultColWidth = 0.0, double defaultRowHeight = 15, + quint8 outlineLevelCol = 0, quint8 outlineLevelRow = 0, + bool thickBottom = false, bool thickTop = false, bool zeroHeight = false) + : baseColWidth(baseColWidth) + , customHeight(customHeight) + , defaultColWidth(defaultColWidth) + , defaultRowHeight(defaultRowHeight) + , outlineLevelCol(outlineLevelCol) + , outlineLevelRow(outlineLevelRow) + , thickBottom(thickBottom) + , thickTop(thickTop) + , zeroHeight(zeroHeight) + { } int baseColWidth; @@ -116,11 +112,14 @@ struct XlsxSheetFormatProps struct XlsxRowInfo { - XlsxRowInfo(double height=0, const Format &format=Format(), bool hidden=false) : - customHeight(false), height(height), format(format), hidden(hidden), outlineLevel(0) - , collapsed(false) + XlsxRowInfo(double height = 0, const Format &format = Format(), bool hidden = false) + : customHeight(false) + , height(height) + , format(format) + , hidden(hidden) + , outlineLevel(0) + , collapsed(false) { - } bool customHeight; @@ -133,16 +132,22 @@ struct XlsxRowInfo struct XlsxColumnInfo { - XlsxColumnInfo(int firstColumn=0, int lastColumn=1, double width=0, const Format &format=Format(), bool hidden=false) : - firstColumn(firstColumn), lastColumn(lastColumn), customWidth(false), width(width), format(format), hidden(hidden) - , outlineLevel(0), collapsed(false) + XlsxColumnInfo(int firstColumn = 0, int lastColumn = 1, double width = 0, + const Format &format = Format(), bool hidden = false) + : firstColumn(firstColumn) + , lastColumn(lastColumn) + , customWidth(false) + , width(width) + , format(format) + , hidden(hidden) + , outlineLevel(0) + , collapsed(false) { - } int firstColumn; int lastColumn; bool customWidth; - double width; + double width; Format format; bool hidden; int outlineLevel; @@ -155,7 +160,7 @@ class XLSX_AUTOTEST_EXPORT WorksheetPrivate : public AbstractSheetPrivate public: WorksheetPrivate(Worksheet *p, Worksheet::CreateFlag flag); ~WorksheetPrivate(); - int checkDimensions(int row, int col, bool ignore_row=false, bool ignore_col=false); + int checkDimensions(int row, int col, bool ignore_row = false, bool ignore_col = false); Format cellFormat(int row, int col) const; QString generateDimensionString() const; void calculateSpans() const; @@ -163,7 +168,8 @@ public: void validateDimension(); void saveXmlSheetData(QXmlStreamWriter &writer) const; - void saveXmlCellData(QXmlStreamWriter &writer, int row, int col, QSharedPointer cell) const; + void saveXmlCellData(QXmlStreamWriter &writer, int row, int col, + QSharedPointer cell) const; void saveXmlMergeCells(QXmlStreamWriter &writer) const; void saveXmlHyperlinks(QXmlStreamWriter &writer) const; void saveXmlDrawings(QXmlStreamWriter &writer) const; @@ -179,20 +185,20 @@ public: void loadXmlSheetViews(QXmlStreamReader &reader); void loadXmlHyperlinks(QXmlStreamReader &reader); - QList > getRowInfoList(int rowFirst, int rowLast); - QList > getColumnInfoList(int colFirst, int colLast); + QList> getRowInfoList(int rowFirst, int rowLast); + QList> getColumnInfoList(int colFirst, int colLast); QList getColumnIndexes(int colFirst, int colLast); bool isColumnRangeValid(int colFirst, int colLast); SharedStrings *sharedStrings() const; - QMap > > cellTable; - QMap > comments; - QMap > > urlTable; + QMap>> cellTable; + QMap> comments; + QMap>> urlTable; QList merges; - QMap > rowsInfo; - QMap > colsInfo; - QMap > colsInfoHelper; + QMap> rowsInfo; + QMap> colsInfo; + QMap> colsInfoHelper; QList dataValidationsList; QList conditionalFormattingList; @@ -225,9 +231,9 @@ public: bool showWhiteSpace; QRegularExpression urlPattern; + private: static double calculateColWidth(int characters); }; - } #endif // XLSXWORKSHEET_P_H diff --git a/src/xlsx/xlsxzipreader.cpp b/src/xlsx/xlsxzipreader.cpp index 6753507..9813dfc 100644 --- a/src/xlsx/xlsxzipreader.cpp +++ b/src/xlsx/xlsxzipreader.cpp @@ -30,21 +30,20 @@ namespace QXlsx { -ZipReader::ZipReader(const QString &filePath) : - m_reader(new QZipReader(filePath)) +ZipReader::ZipReader(const QString &filePath) + : m_reader(new QZipReader(filePath)) { init(); } -ZipReader::ZipReader(QIODevice *device) : - m_reader(new QZipReader(device)) +ZipReader::ZipReader(QIODevice *device) + : m_reader(new QZipReader(device)) { init(); } ZipReader::~ZipReader() { - } void ZipReader::init()