workbook.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716
  1. // Copyright (c) 2014-2021 Thomas Fussell
  2. // Copyright (c) 2010-2015 openpyxl
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE
  21. //
  22. // @license: http://www.opensource.org/licenses/mit-license.php
  23. // @author: see AUTHORS file
  24. #include <algorithm>
  25. #include <array>
  26. #include <fstream>
  27. #include <functional>
  28. #include <set>
  29. #include <xlnt/cell/cell.hpp>
  30. #include <xlnt/packaging/manifest.hpp>
  31. #include <xlnt/packaging/relationship.hpp>
  32. #include <xlnt/styles/alignment.hpp>
  33. #include <xlnt/styles/border.hpp>
  34. #include <xlnt/styles/fill.hpp>
  35. #include <xlnt/styles/font.hpp>
  36. #include <xlnt/styles/format.hpp>
  37. #include <xlnt/styles/number_format.hpp>
  38. #include <xlnt/styles/protection.hpp>
  39. #include <xlnt/styles/style.hpp>
  40. #include <xlnt/utils/exceptions.hpp>
  41. #include <xlnt/utils/path.hpp>
  42. #include <xlnt/utils/variant.hpp>
  43. #include <xlnt/workbook/metadata_property.hpp>
  44. #include <xlnt/workbook/named_range.hpp>
  45. #include <xlnt/workbook/theme.hpp>
  46. #include <xlnt/workbook/workbook.hpp>
  47. #include <xlnt/workbook/workbook_view.hpp>
  48. #include <xlnt/workbook/worksheet_iterator.hpp>
  49. #include <xlnt/worksheet/header_footer.hpp>
  50. #include <xlnt/worksheet/range.hpp>
  51. #include <xlnt/worksheet/worksheet.hpp>
  52. #include <detail/constants.hpp>
  53. #include <detail/default_case.hpp>
  54. #include <detail/implementations/cell_impl.hpp>
  55. #include <detail/implementations/workbook_impl.hpp>
  56. #include <detail/implementations/worksheet_impl.hpp>
  57. #include <detail/serialization/excel_thumbnail.hpp>
  58. #include <detail/serialization/open_stream.hpp>
  59. #include <detail/serialization/vector_streambuf.hpp>
  60. #include <detail/serialization/xlsx_consumer.hpp>
  61. #include <detail/serialization/xlsx_producer.hpp>
  62. namespace {
  63. using xlnt::detail::open_stream;
  64. template <typename T>
  65. std::vector<T> keys(const std::vector<std::pair<T, xlnt::variant>> &container)
  66. {
  67. auto result = std::vector<T>();
  68. auto iter = container.begin();
  69. while (iter != container.end())
  70. {
  71. result.push_back((iter++)->first);
  72. }
  73. return result;
  74. }
  75. template <typename T>
  76. bool contains(const std::vector<std::pair<T, xlnt::variant>> &container, const T key)
  77. {
  78. for (const auto &iter : container)
  79. {
  80. if (iter.first == key)
  81. {
  82. return true;
  83. }
  84. }
  85. return false;
  86. }
  87. xlnt::path default_path(xlnt::relationship_type type, std::size_t index = 0)
  88. {
  89. using xlnt::path;
  90. using xlnt::relationship_type;
  91. switch (type)
  92. {
  93. case relationship_type::calculation_chain:
  94. return path("/xl/calcChain.xml");
  95. case relationship_type::chartsheet:
  96. return path("/xl/sheets/.xml");
  97. case relationship_type::comments:
  98. return path("/xl/comments.xml");
  99. case relationship_type::connections:
  100. return path("/xl/connections.xml");
  101. case relationship_type::core_properties:
  102. return path("/docProps/core.xml");
  103. case relationship_type::custom_properties:
  104. return path("/docProps/custom.xml");
  105. case relationship_type::custom_property:
  106. return path("/xl/customProperty.xml");
  107. case relationship_type::custom_xml_mappings:
  108. return path("/xl/customXmlMappings.xml");
  109. case relationship_type::dialogsheet:
  110. return path("/xl/dialogsheets/sheet.xml");
  111. case relationship_type::drawings:
  112. return path("/xl/drawings/drawing.xml");
  113. case relationship_type::extended_properties:
  114. return path("/docProps/app.xml");
  115. case relationship_type::external_workbook_references:
  116. return path("/xl/external.xml");
  117. case relationship_type::hyperlink:
  118. return path("/xl/hyperlink.xml");
  119. case relationship_type::image:
  120. return path("?");
  121. case relationship_type::office_document:
  122. return path("/xl/workbook.xml");
  123. case relationship_type::pivot_table:
  124. return path("/xl/pivotTable.xml");
  125. case relationship_type::pivot_table_cache_definition:
  126. return path("?");
  127. case relationship_type::pivot_table_cache_records:
  128. return path("?");
  129. case relationship_type::printer_settings:
  130. return path("/xl/printerSettings.xml");
  131. case relationship_type::query_table:
  132. return path("/xl/queryTable.xml");
  133. case relationship_type::revision_log:
  134. return path("/xl/revisionLog.xml");
  135. case relationship_type::shared_string_table:
  136. return path("/xl/sharedStrings.xml");
  137. case relationship_type::shared_workbook:
  138. return path("/xl/sharedWorkbook.xml");
  139. case relationship_type::shared_workbook_revision_headers:
  140. return path("?");
  141. case relationship_type::shared_workbook_user_data:
  142. return path("?");
  143. case relationship_type::single_cell_table_definitions:
  144. return path("?");
  145. case relationship_type::stylesheet:
  146. return path("/xl/styles.xml");
  147. case relationship_type::table_definition:
  148. return path("/xl/tableDefinition.xml");
  149. case relationship_type::theme:
  150. return path("/xl/theme/theme1.xml");
  151. case relationship_type::thumbnail:
  152. return path("/docProps/thumbnail.jpg");
  153. case relationship_type::unknown:
  154. return path("/xl/unknown.xml");
  155. case relationship_type::vml_drawing:
  156. return path("/xl/vmlDrawing.xml");
  157. case relationship_type::volatile_dependencies:
  158. return path("/xl/volatileDependencies.xml");
  159. case relationship_type::vbaproject:
  160. return path("/xl/vbaProject.bin");
  161. case relationship_type::worksheet:
  162. return path("/xl/worksheets/sheet" + std::to_string(index) + ".xml");
  163. }
  164. default_case(path("/xl/unknownPart.xml"));
  165. }
  166. std::string content_type(xlnt::relationship_type type)
  167. {
  168. using xlnt::relationship_type;
  169. switch (type)
  170. {
  171. case relationship_type::calculation_chain:
  172. return "application/vnd.openxmlformats-officedocument.spreadsheetml.calcChain+xml";
  173. case relationship_type::chartsheet:
  174. return "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml";
  175. case relationship_type::comments:
  176. return "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml";
  177. case relationship_type::connections:
  178. return "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml";
  179. case relationship_type::core_properties:
  180. return "application/vnd.openxmlformats-package.core-properties+xml";
  181. case relationship_type::custom_properties:
  182. return "application/vnd.openxmlformats-officedocument.custom-properties+xml";
  183. case relationship_type::custom_property:
  184. throw xlnt::unhandled_switch_case();
  185. case relationship_type::custom_xml_mappings:
  186. return "application/xml";
  187. case relationship_type::dialogsheet:
  188. return "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml";
  189. case relationship_type::drawings:
  190. return "application/vnd.openxmlformats-officedocument.drawing+xml";
  191. case relationship_type::extended_properties:
  192. return "application/vnd.openxmlformats-officedocument.extended-properties+xml";
  193. case relationship_type::external_workbook_references:
  194. return "application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml";
  195. case relationship_type::hyperlink:
  196. throw xlnt::unhandled_switch_case();
  197. case relationship_type::image:
  198. throw xlnt::unhandled_switch_case();
  199. case relationship_type::office_document:
  200. return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml";
  201. case relationship_type::pivot_table:
  202. return "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml";
  203. case relationship_type::pivot_table_cache_definition:
  204. return "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml";
  205. case relationship_type::pivot_table_cache_records:
  206. return "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml";
  207. case relationship_type::printer_settings:
  208. return "application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings";
  209. case relationship_type::query_table:
  210. return "application/vnd.openxmlformats-officedocument.spreadsheetml.queryTable+xml";
  211. case relationship_type::revision_log:
  212. return "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionLog+xml";
  213. case relationship_type::shared_string_table:
  214. return "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml";
  215. case relationship_type::shared_workbook:
  216. throw xlnt::unhandled_switch_case();
  217. case relationship_type::shared_workbook_revision_headers:
  218. return "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionHeaders+xml";
  219. case relationship_type::shared_workbook_user_data:
  220. return "application/vnd.openxmlformats-officedocument.spreadsheetml.userNames+xml";
  221. case relationship_type::single_cell_table_definitions:
  222. return "application/vnd.openxmlformats-officedocument.spreadsheetml.tableSingleCells+xml";
  223. case relationship_type::stylesheet:
  224. return "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml";
  225. case relationship_type::table_definition:
  226. return "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml";
  227. case relationship_type::theme:
  228. return "application/vnd.openxmlformats-officedocument.theme+xml";
  229. case relationship_type::thumbnail:
  230. return "image/jpeg";
  231. case relationship_type::unknown:
  232. return "";
  233. case relationship_type::vml_drawing:
  234. return "application/vnd.openxmlformats-officedocument.vmlDrawing";
  235. case relationship_type::volatile_dependencies:
  236. return "application/vnd.openxmlformats-officedocument.spreadsheetml.volatileDependencies+xml";
  237. case relationship_type::vbaproject:
  238. return "application/vnd.ms-office.vbaProject";
  239. case relationship_type::worksheet:
  240. return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml";
  241. }
  242. default_case("application/xml");
  243. }
  244. } // namespace
  245. namespace xlnt {
  246. bool workbook::has_core_property(xlnt::core_property type) const
  247. {
  248. return ::contains(d_->core_properties_, type);
  249. }
  250. std::vector<xlnt::core_property> workbook::core_properties() const
  251. {
  252. return keys(d_->core_properties_);
  253. }
  254. variant workbook::core_property(xlnt::core_property type) const
  255. {
  256. for (auto iter : d_->core_properties_)
  257. {
  258. if (iter.first == type)
  259. {
  260. return iter.second;
  261. }
  262. }
  263. throw xlnt::exception("workbook doesn't have core property");
  264. }
  265. void workbook::core_property(xlnt::core_property type, const variant &value)
  266. {
  267. register_package_part(relationship_type::core_properties);
  268. for (auto &iter : d_->core_properties_)
  269. {
  270. if (iter.first == type)
  271. {
  272. iter.second = value;
  273. return;
  274. }
  275. }
  276. d_->core_properties_.push_back({type, value});
  277. }
  278. bool workbook::has_extended_property(xlnt::extended_property type) const
  279. {
  280. return ::contains(d_->extended_properties_, type);
  281. }
  282. std::vector<xlnt::extended_property> workbook::extended_properties() const
  283. {
  284. return keys(d_->extended_properties_);
  285. }
  286. void workbook::extended_property(xlnt::extended_property type, const variant &value)
  287. {
  288. register_package_part(relationship_type::extended_properties);
  289. for (auto &iter : d_->extended_properties_)
  290. {
  291. if (iter.first == type)
  292. {
  293. iter.second = value;
  294. return;
  295. }
  296. }
  297. d_->extended_properties_.push_back({type, value});
  298. }
  299. variant workbook::extended_property(xlnt::extended_property type) const
  300. {
  301. for (auto iter : d_->extended_properties_)
  302. {
  303. if (iter.first == type)
  304. {
  305. return iter.second;
  306. }
  307. }
  308. throw xlnt::exception("workbook doesn't have extended property");
  309. }
  310. bool workbook::has_custom_property(const std::string &property_name) const
  311. {
  312. return ::contains(d_->custom_properties_, property_name);
  313. }
  314. std::vector<std::string> workbook::custom_properties() const
  315. {
  316. return keys(d_->custom_properties_);
  317. }
  318. void workbook::custom_property(const std::string &property_name, const variant &value)
  319. {
  320. register_package_part(relationship_type::custom_properties);
  321. for (auto &iter : d_->custom_properties_)
  322. {
  323. if (iter.first == property_name)
  324. {
  325. iter.second = value;
  326. return;
  327. }
  328. }
  329. d_->custom_properties_.push_back({property_name, value});
  330. }
  331. variant workbook::custom_property(const std::string &property_name) const
  332. {
  333. for (auto iter : d_->custom_properties_)
  334. {
  335. if (iter.first == property_name)
  336. {
  337. return iter.second;
  338. }
  339. }
  340. throw xlnt::exception("workbook doesn't have custom property");
  341. }
  342. void workbook::abs_path(const std::string &path)
  343. {
  344. d_->abs_path_ = path;
  345. }
  346. void workbook::arch_id_flags(const std::size_t flags)
  347. {
  348. d_->arch_id_flags_ = flags;
  349. }
  350. workbook workbook::empty()
  351. {
  352. auto impl = new detail::workbook_impl();
  353. workbook wb(impl);
  354. wb.register_package_part(relationship_type::office_document);
  355. wb.d_->manifest_.register_default_type("rels",
  356. "application/vnd.openxmlformats-package.relationships+xml");
  357. wb.d_->manifest_.register_default_type("xml",
  358. "application/xml");
  359. wb.thumbnail(excel_thumbnail(), "jpeg", "image/jpeg");
  360. wb.core_property(xlnt::core_property::creator, "Microsoft Office User");
  361. wb.core_property(xlnt::core_property::last_modified_by, "Microsoft Office User");
  362. wb.core_property(xlnt::core_property::created, datetime(2016, 8, 12, 3, 16, 56));
  363. wb.core_property(xlnt::core_property::modified, datetime(2016, 8, 12, 3, 17, 16));
  364. wb.extended_property(xlnt::extended_property::application, "Microsoft Macintosh Excel");
  365. wb.extended_property(xlnt::extended_property::doc_security, 0);
  366. wb.extended_property(xlnt::extended_property::scale_crop, false);
  367. wb.extended_property(xlnt::extended_property::heading_pairs, std::vector<variant>{variant("Worksheets"), variant(1)});
  368. wb.extended_property(xlnt::extended_property::titles_of_parts, {"Sheet1"});
  369. wb.extended_property(xlnt::extended_property::company, "");
  370. wb.extended_property(xlnt::extended_property::links_up_to_date, false);
  371. wb.extended_property(xlnt::extended_property::shared_doc, false);
  372. wb.extended_property(xlnt::extended_property::hyperlinks_changed, false);
  373. wb.extended_property(xlnt::extended_property::app_version, "15.0300");
  374. detail::workbook_impl::file_version_t file_version;
  375. file_version.app_name = "xl";
  376. file_version.last_edited = 6;
  377. file_version.lowest_edited = 6;
  378. file_version.rup_build = 26709;
  379. wb.d_->file_version_ = file_version;
  380. xlnt::workbook_view wb_view;
  381. wb_view.active_tab = 0;
  382. wb_view.x_window = 0;
  383. wb_view.y_window = 460;
  384. wb_view.window_width = 28800;
  385. wb_view.window_height = 17460;
  386. wb_view.tab_ratio = 500;
  387. wb.view(wb_view);
  388. auto ws = wb.create_sheet();
  389. page_margins margins;
  390. margins.left(0.7);
  391. margins.right(0.7);
  392. margins.top(0.75);
  393. margins.bottom(0.75);
  394. margins.header(0.3);
  395. margins.footer(0.3);
  396. ws.page_margins(margins);
  397. sheet_view view;
  398. ws.add_view(view);
  399. auto &format_properties = ws.d_->format_properties_;
  400. format_properties.base_col_width = 10.0;
  401. format_properties.default_row_height = 16.0;
  402. wb.theme(xlnt::theme());
  403. wb.d_->stylesheet_ = detail::stylesheet();
  404. auto &stylesheet = wb.d_->stylesheet_.get();
  405. stylesheet.parent = &wb;
  406. auto default_border = border()
  407. .side(border_side::bottom, border::border_property())
  408. .side(border_side::top, border::border_property())
  409. .side(border_side::start, border::border_property())
  410. .side(border_side::end, border::border_property())
  411. .side(border_side::diagonal, border::border_property());
  412. wb.d_->stylesheet_.get().borders.push_back(default_border);
  413. auto default_fill = fill(pattern_fill()
  414. .type(pattern_fill_type::none));
  415. stylesheet.fills.push_back(default_fill);
  416. auto gray125_fill = pattern_fill()
  417. .type(pattern_fill_type::gray125);
  418. stylesheet.fills.push_back(gray125_fill);
  419. auto default_font = font()
  420. .name("Calibri")
  421. .size(12)
  422. .scheme("minor")
  423. .family(2)
  424. .color(theme_color(1));
  425. stylesheet.fonts.push_back(default_font);
  426. wb.create_builtin_style(0)
  427. .border(default_border)
  428. .fill(default_fill)
  429. .font(default_font)
  430. .number_format(xlnt::number_format::general());
  431. wb.create_format(true)
  432. .border(default_border)
  433. .fill(default_fill)
  434. .font(default_font)
  435. .number_format(xlnt::number_format::general())
  436. .style("Normal");
  437. xlnt::calculation_properties calc_props;
  438. calc_props.calc_id = 150000;
  439. calc_props.concurrent_calc = false;
  440. wb.calculation_properties(calc_props);
  441. return wb;
  442. }
  443. workbook::workbook()
  444. {
  445. auto wb_template = empty();
  446. swap(wb_template);
  447. }
  448. workbook::workbook(const xlnt::path &file)
  449. {
  450. *this = empty();
  451. load(file);
  452. }
  453. workbook::workbook(const xlnt::path &file, const std::string &password)
  454. {
  455. *this = empty();
  456. load(file, password);
  457. }
  458. workbook::workbook(std::istream &data)
  459. {
  460. *this = empty();
  461. load(data);
  462. }
  463. workbook::workbook(std::istream &data, const std::string &password)
  464. {
  465. *this = empty();
  466. load(data, password);
  467. }
  468. workbook::workbook(detail::workbook_impl *impl)
  469. : d_(impl)
  470. {
  471. if (impl != nullptr)
  472. {
  473. if (d_->stylesheet_.is_set())
  474. {
  475. d_->stylesheet_.get().parent = this;
  476. }
  477. }
  478. }
  479. void workbook::register_package_part(relationship_type type)
  480. {
  481. if (!manifest().has_relationship(path("/"), type))
  482. {
  483. manifest().register_override_type(default_path(type), content_type(type));
  484. manifest().register_relationship(uri("/"), type,
  485. uri(default_path(type).relative_to(path("/")).string()),
  486. target_mode::internal);
  487. }
  488. }
  489. void workbook::register_workbook_part(relationship_type type)
  490. {
  491. auto wb_rel = manifest().relationship(path("/"), relationship_type::office_document);
  492. auto wb_path = manifest().canonicalize({wb_rel});
  493. if (!manifest().has_relationship(wb_path, type))
  494. {
  495. manifest().register_override_type(default_path(type), content_type(type));
  496. manifest().register_relationship(uri(wb_path.string()), type,
  497. uri(default_path(type).relative_to(wb_path.resolve(path("/"))).string()),
  498. target_mode::internal);
  499. }
  500. }
  501. void workbook::register_worksheet_part(worksheet ws, relationship_type type)
  502. {
  503. auto wb_rel = manifest().relationship(path("/"),
  504. relationship_type::office_document);
  505. auto ws_rel = manifest().relationship(wb_rel.target().path(),
  506. d_->sheet_title_rel_id_map_.at(ws.title()));
  507. path ws_path(ws_rel.source().path().parent().append(ws_rel.target().path()));
  508. if (type == relationship_type::comments)
  509. {
  510. if (!manifest().has_relationship(ws_path, relationship_type::vml_drawing))
  511. {
  512. std::size_t file_number = 1;
  513. path filename("vmlDrawing1.vml");
  514. bool filename_exists = true;
  515. while (filename_exists)
  516. {
  517. filename_exists = false;
  518. for (auto current_ws_rel :
  519. manifest().relationships(wb_rel.target().path(), xlnt::relationship_type::worksheet))
  520. {
  521. path current_ws_path(current_ws_rel.source().path().parent().append(current_ws_rel.target().path()));
  522. if (!manifest().has_relationship(current_ws_path, xlnt::relationship_type::vml_drawing)) continue;
  523. for (auto current_ws_child_rel :
  524. manifest().relationships(current_ws_path, xlnt::relationship_type::vml_drawing))
  525. {
  526. if (current_ws_child_rel.target().path() == path("../drawings").append(filename))
  527. {
  528. filename_exists = true;
  529. break;
  530. }
  531. }
  532. }
  533. if (filename_exists)
  534. {
  535. file_number++;
  536. filename = path("vmlDrawing" + std::to_string(file_number) + ".vml");
  537. }
  538. }
  539. manifest().register_default_type("vml", "application/vnd.openxmlformats-officedocument.vmlDrawing");
  540. const path relative_path(path("../drawings").append(filename));
  541. manifest().register_relationship(
  542. uri(ws_path.string()), relationship_type::vml_drawing, uri(relative_path.string()), target_mode::internal);
  543. }
  544. if (!manifest().has_relationship(ws_path, relationship_type::comments))
  545. {
  546. std::size_t file_number = 1;
  547. path filename("comments1.xml");
  548. while (true)
  549. {
  550. if (!manifest().has_override_type(constants::package_xl().append(filename))) break;
  551. file_number++;
  552. filename = path("comments" + std::to_string(file_number) + ".xml");
  553. }
  554. const path absolute_path(constants::package_xl().append(filename));
  555. manifest().register_override_type(
  556. absolute_path, "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml");
  557. const path relative_path(path("..").append(filename));
  558. manifest().register_relationship(
  559. uri(ws_path.string()), relationship_type::comments, uri(relative_path.string()), target_mode::internal);
  560. }
  561. }
  562. }
  563. const worksheet workbook::sheet_by_title(const std::string &title) const
  564. {
  565. for (auto &impl : d_->worksheets_)
  566. {
  567. if (impl.title_ == title)
  568. {
  569. return worksheet(&impl);
  570. }
  571. }
  572. throw key_not_found();
  573. }
  574. worksheet workbook::sheet_by_title(const std::string &title)
  575. {
  576. for (auto &impl : d_->worksheets_)
  577. {
  578. if (impl.title_ == title)
  579. {
  580. return worksheet(&impl);
  581. }
  582. }
  583. throw key_not_found();
  584. }
  585. worksheet workbook::sheet_by_index(std::size_t index)
  586. {
  587. if (index >= d_->worksheets_.size())
  588. {
  589. throw invalid_parameter();
  590. }
  591. auto iter = d_->worksheets_.begin();
  592. for (std::size_t i = 0; i < index; ++i)
  593. {
  594. ++iter;
  595. }
  596. return worksheet(&*iter);
  597. }
  598. const worksheet workbook::sheet_by_index(std::size_t index) const
  599. {
  600. if (index >= d_->worksheets_.size())
  601. {
  602. throw invalid_parameter();
  603. }
  604. auto iter = d_->worksheets_.begin();
  605. for (std::size_t i = 0; i < index; ++i, ++iter)
  606. {
  607. }
  608. return worksheet(&*iter);
  609. }
  610. worksheet workbook::sheet_by_id(std::size_t id)
  611. {
  612. for (auto &impl : d_->worksheets_)
  613. {
  614. if (impl.id_ == id)
  615. {
  616. return worksheet(&impl);
  617. }
  618. }
  619. throw key_not_found();
  620. }
  621. const worksheet workbook::sheet_by_id(std::size_t id) const
  622. {
  623. for (auto &impl : d_->worksheets_)
  624. {
  625. if (impl.id_ == id)
  626. {
  627. return worksheet(&impl);
  628. }
  629. }
  630. throw key_not_found();
  631. }
  632. bool workbook::sheet_hidden_by_index(std::size_t index) const
  633. {
  634. if (index >= d_->sheet_hidden_.size())
  635. {
  636. throw invalid_parameter();
  637. }
  638. return d_->sheet_hidden_.at(index);
  639. }
  640. worksheet workbook::active_sheet()
  641. {
  642. return sheet_by_index(d_->active_sheet_index_.is_set() ? d_->active_sheet_index_.get() : 0);
  643. }
  644. void workbook::active_sheet(std::size_t index)
  645. {
  646. d_->active_sheet_index_.set(index);
  647. d_->view_.get().active_tab = index;
  648. }
  649. bool workbook::has_named_range(const std::string &name) const
  650. {
  651. for (auto worksheet : *this)
  652. {
  653. if (worksheet.has_named_range(name))
  654. {
  655. return true;
  656. }
  657. }
  658. return false;
  659. }
  660. worksheet workbook::create_sheet()
  661. {
  662. std::string title = "Sheet1";
  663. int index = 1;
  664. // make a unique sheet name. Sheet<1...n>
  665. while (contains(title))
  666. {
  667. title = "Sheet" + std::to_string(++index);
  668. }
  669. // unique sheet id
  670. size_t sheet_id = 1;
  671. for (const auto ws : *this)
  672. {
  673. sheet_id = std::max(sheet_id, ws.id() + 1);
  674. }
  675. d_->worksheets_.push_back(detail::worksheet_impl(this, sheet_id, title));
  676. // unique sheet file name
  677. auto workbook_rel = d_->manifest_.relationship(path("/"), relationship_type::office_document);
  678. auto workbook_files = d_->manifest_.relationships(workbook_rel.target().path());
  679. auto rel_vec_contains = [&workbook_files](const xlnt::path &new_file_id) {
  680. return workbook_files.end() != std::find_if(workbook_files.begin(), workbook_files.end(), [&new_file_id](const xlnt::relationship &rel) {
  681. return rel.target().path() == new_file_id;
  682. });
  683. };
  684. size_t file_id = sheet_id;
  685. xlnt::path sheet_relative_path;
  686. do
  687. {
  688. sheet_relative_path = path("worksheets").append("sheet" + std::to_string(file_id++) + ".xml");
  689. } while (rel_vec_contains(sheet_relative_path));
  690. uri relative_sheet_uri(sheet_relative_path.string());
  691. auto absolute_sheet_path = path("/xl").append(relative_sheet_uri.path());
  692. d_->manifest_.register_override_type(
  693. absolute_sheet_path, "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml");
  694. auto ws_rel = d_->manifest_.register_relationship(
  695. workbook_rel.target(), relationship_type::worksheet, relative_sheet_uri, target_mode::internal);
  696. d_->sheet_title_rel_id_map_[title] = ws_rel;
  697. update_sheet_properties();
  698. reorder_relationships();
  699. return worksheet(&d_->worksheets_.back());
  700. }
  701. worksheet workbook::copy_sheet(worksheet to_copy)
  702. {
  703. if (to_copy.d_->parent_ != this) throw invalid_parameter();
  704. detail::worksheet_impl impl(*to_copy.d_);
  705. auto new_sheet = create_sheet();
  706. impl.title_ = new_sheet.title();
  707. impl.id_ = new_sheet.id();
  708. *new_sheet.d_ = impl;
  709. return new_sheet;
  710. }
  711. worksheet workbook::copy_sheet(worksheet to_copy, std::size_t index)
  712. {
  713. copy_sheet(to_copy);
  714. if (index != d_->worksheets_.size() - 1)
  715. {
  716. auto iter = d_->worksheets_.begin();
  717. for (std::size_t i = 0; i < index; ++i, ++iter)
  718. {
  719. }
  720. d_->worksheets_.insert(iter, d_->worksheets_.back());
  721. d_->worksheets_.pop_back();
  722. }
  723. return sheet_by_index(index);
  724. }
  725. std::size_t workbook::index(worksheet ws)
  726. {
  727. auto match = std::find(begin(), end(), ws);
  728. if (match == end())
  729. {
  730. throw invalid_parameter();
  731. }
  732. return static_cast<std::size_t>(std::distance(begin(), match));
  733. }
  734. void workbook::create_named_range(const std::string &name, worksheet range_owner, const std::string &reference_string)
  735. {
  736. create_named_range(name, range_owner, range_reference(reference_string));
  737. }
  738. void workbook::create_named_range(const std::string &name, worksheet range_owner, const range_reference &reference)
  739. {
  740. sheet_by_title(range_owner.title()).create_named_range(name, reference);
  741. }
  742. void workbook::remove_named_range(const std::string &name)
  743. {
  744. for (auto ws : *this)
  745. {
  746. if (ws.has_named_range(name))
  747. {
  748. ws.remove_named_range(name);
  749. return;
  750. }
  751. }
  752. throw key_not_found();
  753. }
  754. range workbook::named_range(const std::string &name)
  755. {
  756. for (auto ws : *this)
  757. {
  758. if (ws.has_named_range(name))
  759. {
  760. return ws.named_range(name);
  761. }
  762. }
  763. throw key_not_found();
  764. }
  765. void workbook::load(std::istream &stream)
  766. {
  767. clear();
  768. detail::xlsx_consumer consumer(*this);
  769. try
  770. {
  771. consumer.read(stream);
  772. }
  773. catch (xlnt::exception &e)
  774. {
  775. if (e.what() == std::string("xlnt::exception : encrypted xlsx, password required"))
  776. {
  777. stream.seekg(0, std::ios::beg);
  778. consumer.read(stream, "VelvetSweatshop");
  779. }
  780. else
  781. {
  782. throw;
  783. }
  784. }
  785. }
  786. void workbook::load(const std::vector<std::uint8_t> &data)
  787. {
  788. if (data.size() < 22) // the shortest ZIP file is 22 bytes
  789. {
  790. throw xlnt::exception("file is empty or malformed");
  791. }
  792. xlnt::detail::vector_istreambuf data_buffer(data);
  793. std::istream data_stream(&data_buffer);
  794. load(data_stream);
  795. }
  796. void workbook::load(const std::string &filename)
  797. {
  798. return load(path(filename));
  799. }
  800. void workbook::load(const path &filename)
  801. {
  802. std::ifstream file_stream;
  803. open_stream(file_stream, filename.string());
  804. if (!file_stream.good())
  805. {
  806. throw xlnt::exception("file not found " + filename.string());
  807. }
  808. load(file_stream);
  809. }
  810. void workbook::load(const std::string &filename, const std::string &password)
  811. {
  812. return load(path(filename), password);
  813. }
  814. void workbook::load(const path &filename, const std::string &password)
  815. {
  816. std::ifstream file_stream;
  817. open_stream(file_stream, filename.string());
  818. if (!file_stream.good())
  819. {
  820. throw xlnt::exception("file not found " + filename.string());
  821. }
  822. return load(file_stream, password);
  823. }
  824. void workbook::load(const std::vector<std::uint8_t> &data, const std::string &password)
  825. {
  826. if (data.size() < 22) // the shortest ZIP file is 22 bytes
  827. {
  828. throw xlnt::exception("file is empty or malformed");
  829. }
  830. xlnt::detail::vector_istreambuf data_buffer(data);
  831. std::istream data_stream(&data_buffer);
  832. load(data_stream, password);
  833. }
  834. void workbook::load(std::istream &stream, const std::string &password)
  835. {
  836. clear();
  837. detail::xlsx_consumer consumer(*this);
  838. consumer.read(stream, password);
  839. }
  840. void workbook::save(std::vector<std::uint8_t> &data) const
  841. {
  842. xlnt::detail::vector_ostreambuf data_buffer(data);
  843. std::ostream data_stream(&data_buffer);
  844. save(data_stream);
  845. }
  846. void workbook::save(std::vector<std::uint8_t> &data, const std::string &password) const
  847. {
  848. xlnt::detail::vector_ostreambuf data_buffer(data);
  849. std::ostream data_stream(&data_buffer);
  850. save(data_stream, password);
  851. }
  852. void workbook::save(const std::string &filename) const
  853. {
  854. save(path(filename));
  855. }
  856. void workbook::save(const std::string &filename, const std::string &password) const
  857. {
  858. save(path(filename), password);
  859. }
  860. void workbook::save(const path &filename) const
  861. {
  862. std::ofstream file_stream;
  863. open_stream(file_stream, filename.string());
  864. save(file_stream);
  865. }
  866. void workbook::save(const path &filename, const std::string &password) const
  867. {
  868. std::ofstream file_stream;
  869. open_stream(file_stream, filename.string());
  870. save(file_stream, password);
  871. }
  872. void workbook::save(std::ostream &stream) const
  873. {
  874. detail::xlsx_producer producer(*this);
  875. producer.write(stream);
  876. }
  877. void workbook::save(std::ostream &stream, const std::string &password) const
  878. {
  879. detail::xlsx_producer producer(*this);
  880. producer.write(stream, password);
  881. }
  882. #ifdef _MSC_VER
  883. void workbook::save(const std::wstring &filename) const
  884. {
  885. std::ofstream file_stream;
  886. open_stream(file_stream, filename);
  887. save(file_stream);
  888. }
  889. void workbook::save(const std::wstring &filename, const std::string &password) const
  890. {
  891. std::ofstream file_stream;
  892. open_stream(file_stream, filename);
  893. save(file_stream, password);
  894. }
  895. void workbook::load(const std::wstring &filename)
  896. {
  897. std::ifstream file_stream;
  898. open_stream(file_stream, filename);
  899. load(file_stream);
  900. }
  901. void workbook::load(const std::wstring &filename, const std::string &password)
  902. {
  903. std::ifstream file_stream;
  904. open_stream(file_stream, filename);
  905. load(file_stream, password);
  906. }
  907. #endif
  908. void workbook::remove_sheet(worksheet ws)
  909. {
  910. auto match_iter = std::find_if(d_->worksheets_.begin(), d_->worksheets_.end(),
  911. [=](detail::worksheet_impl &comp) { return &comp == ws.d_; });
  912. if (match_iter == d_->worksheets_.end())
  913. {
  914. throw invalid_parameter();
  915. }
  916. auto ws_rel_id = d_->sheet_title_rel_id_map_.at(ws.title());
  917. auto wb_rel = d_->manifest_.relationship(path("/"), xlnt::relationship_type::office_document);
  918. auto ws_rel = d_->manifest_.relationship(wb_rel.target().path(), ws_rel_id);
  919. auto ws_part = d_->manifest_.canonicalize({wb_rel, ws_rel}).resolve(path("/"));
  920. d_->manifest_.unregister_override_type(ws_part);
  921. auto rel_id_map = d_->manifest_.unregister_relationship(wb_rel.target(), ws_rel_id);
  922. d_->sheet_title_rel_id_map_.erase(ws.title());
  923. d_->worksheets_.erase(match_iter);
  924. // Shift sheet title->ID mappings down as a result of manifest::unregister_relationship above.
  925. for (auto &title_rel_id_pair : d_->sheet_title_rel_id_map_)
  926. {
  927. title_rel_id_pair.second = rel_id_map.count(title_rel_id_pair.second) > 0
  928. ? rel_id_map[title_rel_id_pair.second]
  929. : title_rel_id_pair.second;
  930. }
  931. update_sheet_properties();
  932. }
  933. worksheet workbook::create_sheet(std::size_t index)
  934. {
  935. create_sheet();
  936. if (index != d_->worksheets_.size() - 1)
  937. {
  938. auto iter = d_->worksheets_.begin();
  939. for (std::size_t i = 0; i < index; ++i, ++iter)
  940. {
  941. }
  942. d_->worksheets_.insert(iter, d_->worksheets_.back());
  943. d_->worksheets_.pop_back();
  944. }
  945. return sheet_by_index(index);
  946. }
  947. worksheet workbook::create_sheet_with_rel(const std::string &title, const relationship &rel)
  948. {
  949. auto sheet_id = d_->worksheets_.size() + 1;
  950. d_->worksheets_.push_back(detail::worksheet_impl(this, sheet_id, title));
  951. auto workbook_rel = d_->manifest_.relationship(path("/"), relationship_type::office_document);
  952. auto sheet_absoulute_path = workbook_rel.target().path().parent().append(rel.target().path());
  953. d_->manifest_.register_override_type(sheet_absoulute_path,
  954. "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml");
  955. auto ws_rel = d_->manifest_.register_relationship(workbook_rel.target(),
  956. relationship_type::worksheet, rel.target(), target_mode::internal);
  957. d_->sheet_title_rel_id_map_[title] = ws_rel;
  958. update_sheet_properties();
  959. return worksheet(&d_->worksheets_.back());
  960. }
  961. workbook::iterator workbook::begin()
  962. {
  963. return iterator(*this, 0);
  964. }
  965. workbook::iterator workbook::end()
  966. {
  967. return iterator(*this, d_->worksheets_.size());
  968. }
  969. workbook::const_iterator workbook::begin() const
  970. {
  971. return cbegin();
  972. }
  973. workbook::const_iterator workbook::end() const
  974. {
  975. return cend();
  976. }
  977. workbook::const_iterator workbook::cbegin() const
  978. {
  979. return const_iterator(*this, 0);
  980. }
  981. workbook::const_iterator workbook::cend() const
  982. {
  983. return const_iterator(*this, d_->worksheets_.size());
  984. }
  985. std::vector<std::string> workbook::sheet_titles() const
  986. {
  987. std::vector<std::string> names;
  988. for (auto ws : *this)
  989. {
  990. names.push_back(ws.title());
  991. }
  992. return names;
  993. }
  994. std::size_t workbook::sheet_count() const
  995. {
  996. return d_->worksheets_.size();
  997. }
  998. worksheet workbook::operator[](const std::string &name)
  999. {
  1000. return sheet_by_title(name);
  1001. }
  1002. worksheet workbook::operator[](std::size_t index)
  1003. {
  1004. return sheet_by_index(index);
  1005. }
  1006. void workbook::clear()
  1007. {
  1008. *d_ = detail::workbook_impl();
  1009. d_->stylesheet_.clear();
  1010. }
  1011. bool workbook::operator==(const workbook &rhs) const
  1012. {
  1013. return *d_ == *rhs.d_;
  1014. }
  1015. bool workbook::operator!=(const workbook &rhs) const
  1016. {
  1017. return !operator==(rhs);
  1018. }
  1019. void workbook::swap(workbook &right)
  1020. {
  1021. auto &left = *this;
  1022. using std::swap;
  1023. swap(left.d_, right.d_);
  1024. if (left.d_ != nullptr)
  1025. {
  1026. for (auto ws : left)
  1027. {
  1028. ws.parent(left);
  1029. }
  1030. if (left.d_->stylesheet_.is_set())
  1031. {
  1032. left.d_->stylesheet_.get().parent = &left;
  1033. }
  1034. }
  1035. if (right.d_ != nullptr)
  1036. {
  1037. for (auto ws : right)
  1038. {
  1039. ws.parent(right);
  1040. }
  1041. if (right.d_->stylesheet_.is_set())
  1042. {
  1043. right.d_->stylesheet_.get().parent = &right;
  1044. }
  1045. }
  1046. }
  1047. workbook &workbook::operator=(workbook other)
  1048. {
  1049. swap(other);
  1050. d_->stylesheet_.get().parent = this;
  1051. return *this;
  1052. }
  1053. workbook::workbook(workbook &&other)
  1054. : workbook(nullptr)
  1055. {
  1056. swap(other);
  1057. }
  1058. workbook::workbook(const workbook &other)
  1059. : workbook()
  1060. {
  1061. *d_.get() = *other.d_.get();
  1062. for (auto ws : *this)
  1063. {
  1064. ws.parent(*this);
  1065. }
  1066. d_->stylesheet_.get().parent = this;
  1067. }
  1068. workbook::~workbook() = default;
  1069. bool workbook::has_theme() const
  1070. {
  1071. return d_->theme_.is_set();
  1072. }
  1073. const theme &workbook::theme() const
  1074. {
  1075. return d_->theme_.get();
  1076. }
  1077. void workbook::theme(const class theme &value)
  1078. {
  1079. d_->theme_ = value;
  1080. register_workbook_part(relationship_type::theme);
  1081. }
  1082. std::vector<named_range> workbook::named_ranges() const
  1083. {
  1084. std::vector<xlnt::named_range> named_ranges;
  1085. for (auto ws : *this)
  1086. {
  1087. for (auto &ws_named_range : ws.d_->named_ranges_)
  1088. {
  1089. named_ranges.push_back(ws_named_range.second);
  1090. }
  1091. }
  1092. return named_ranges;
  1093. }
  1094. format workbook::create_format(bool default_format)
  1095. {
  1096. register_workbook_part(relationship_type::stylesheet);
  1097. return d_->stylesheet_.get().create_format(default_format);
  1098. }
  1099. bool workbook::has_style(const std::string &name) const
  1100. {
  1101. return d_->stylesheet_.get().has_style(name);
  1102. }
  1103. void workbook::clear_styles()
  1104. {
  1105. apply_to_cells([](cell c) { c.clear_style(); });
  1106. }
  1107. void workbook::default_slicer_style(const std::string &value)
  1108. {
  1109. d_->stylesheet_.get().default_slicer_style = value;
  1110. }
  1111. std::string workbook::default_slicer_style() const
  1112. {
  1113. return d_->stylesheet_.get().default_slicer_style.get();
  1114. }
  1115. void workbook::enable_known_fonts()
  1116. {
  1117. d_->stylesheet_.get().known_fonts_enabled = true;
  1118. }
  1119. void workbook::disable_known_fonts()
  1120. {
  1121. d_->stylesheet_.get().known_fonts_enabled = false;
  1122. }
  1123. bool workbook::known_fonts_enabled() const
  1124. {
  1125. return d_->stylesheet_.get().known_fonts_enabled;
  1126. }
  1127. void workbook::clear_formats()
  1128. {
  1129. apply_to_cells([](cell c) { c.clear_format(); });
  1130. }
  1131. void workbook::apply_to_cells(std::function<void(cell)> f)
  1132. {
  1133. for (auto ws : *this)
  1134. {
  1135. for (auto row = ws.lowest_row(); row <= ws.highest_row(); ++row)
  1136. {
  1137. for (auto column = ws.lowest_column(); column <= ws.highest_column(); ++column)
  1138. {
  1139. if (ws.has_cell(cell_reference(column, row)))
  1140. {
  1141. f.operator()(ws.cell(cell_reference(column, row)));
  1142. }
  1143. }
  1144. }
  1145. }
  1146. }
  1147. format workbook::format(std::size_t format_index)
  1148. {
  1149. return d_->stylesheet_.get().format(format_index);
  1150. }
  1151. const format workbook::format(std::size_t format_index) const
  1152. {
  1153. return d_->stylesheet_.get().format(format_index);
  1154. }
  1155. manifest &workbook::manifest()
  1156. {
  1157. return d_->manifest_;
  1158. }
  1159. const manifest &workbook::manifest() const
  1160. {
  1161. return d_->manifest_;
  1162. }
  1163. const rich_text &workbook::shared_strings(std::size_t index) const
  1164. {
  1165. if (index < d_->shared_strings_values_.size())
  1166. {
  1167. return d_->shared_strings_values_.at(index);
  1168. }
  1169. static rich_text empty;
  1170. return empty;
  1171. }
  1172. std::vector<rich_text> &workbook::shared_strings()
  1173. {
  1174. return d_->shared_strings_values_;
  1175. }
  1176. const std::vector<rich_text> &workbook::shared_strings() const
  1177. {
  1178. return d_->shared_strings_values_;
  1179. }
  1180. std::size_t workbook::add_shared_string(const rich_text &shared, bool allow_duplicates)
  1181. {
  1182. register_workbook_part(relationship_type::shared_string_table);
  1183. if (!allow_duplicates)
  1184. {
  1185. auto it = d_->shared_strings_ids_.find(shared);
  1186. if (it != d_->shared_strings_ids_.end())
  1187. {
  1188. return it->second;
  1189. }
  1190. }
  1191. auto sz = d_->shared_strings_ids_.size();
  1192. d_->shared_strings_ids_[shared] = sz;
  1193. d_->shared_strings_values_.push_back(shared);
  1194. return sz;
  1195. }
  1196. bool workbook::contains(const std::string &sheet_title) const
  1197. {
  1198. for (auto ws : *this)
  1199. {
  1200. if (ws.title() == sheet_title) return true;
  1201. }
  1202. return false;
  1203. }
  1204. void workbook::thumbnail(const std::vector<std::uint8_t> &thumbnail,
  1205. const std::string &extension, const std::string &content_type)
  1206. {
  1207. if (!d_->manifest_.has_relationship(path("/"), relationship_type::thumbnail))
  1208. {
  1209. d_->manifest_.register_default_type(extension, content_type);
  1210. d_->manifest_.register_relationship(uri("/"), relationship_type::thumbnail,
  1211. uri("docProps/thumbnail.jpeg"), target_mode::internal);
  1212. }
  1213. auto thumbnail_rel = d_->manifest_.relationship(path("/"), relationship_type::thumbnail);
  1214. d_->images_[thumbnail_rel.target().to_string()] = thumbnail;
  1215. }
  1216. const std::vector<std::uint8_t> &workbook::thumbnail() const
  1217. {
  1218. auto thumbnail_rel = d_->manifest_.relationship(path("/"), relationship_type::thumbnail);
  1219. return d_->images_.at(thumbnail_rel.target().to_string());
  1220. }
  1221. const std::unordered_map<std::string, std::vector<std::uint8_t>> &workbook::binaries() const
  1222. {
  1223. return d_->binaries_;
  1224. }
  1225. style workbook::create_style(const std::string &name)
  1226. {
  1227. return d_->stylesheet_.get().create_style(name);
  1228. }
  1229. style workbook::create_builtin_style(const std::size_t builtin_id)
  1230. {
  1231. return d_->stylesheet_.get().create_builtin_style(builtin_id);
  1232. }
  1233. style workbook::style(const std::string &name)
  1234. {
  1235. return d_->stylesheet_.get().style(name);
  1236. }
  1237. const style workbook::style(const std::string &name) const
  1238. {
  1239. return d_->stylesheet_.get().style(name);
  1240. }
  1241. calendar workbook::base_date() const
  1242. {
  1243. return d_->base_date_;
  1244. }
  1245. void workbook::base_date(calendar base_date)
  1246. {
  1247. d_->base_date_ = base_date;
  1248. }
  1249. bool workbook::has_title() const
  1250. {
  1251. return d_->title_.is_set();
  1252. }
  1253. std::string workbook::title() const
  1254. {
  1255. return d_->title_.get();
  1256. }
  1257. void workbook::title(const std::string &title)
  1258. {
  1259. d_->title_ = title;
  1260. }
  1261. detail::workbook_impl &workbook::impl()
  1262. {
  1263. return *d_;
  1264. }
  1265. const detail::workbook_impl &workbook::impl() const
  1266. {
  1267. return *d_;
  1268. }
  1269. bool workbook::has_view() const
  1270. {
  1271. return d_->view_.is_set();
  1272. }
  1273. workbook_view workbook::view() const
  1274. {
  1275. if (!d_->view_.is_set())
  1276. {
  1277. throw invalid_attribute();
  1278. }
  1279. return d_->view_.get();
  1280. }
  1281. void workbook::view(const workbook_view &view)
  1282. {
  1283. d_->view_ = view;
  1284. }
  1285. bool workbook::has_code_name() const
  1286. {
  1287. return d_->code_name_.is_set();
  1288. }
  1289. std::string workbook::code_name() const
  1290. {
  1291. if (has_code_name())
  1292. {
  1293. throw invalid_attribute();
  1294. }
  1295. return d_->code_name_.get();
  1296. }
  1297. void workbook::code_name(const std::string &code_name)
  1298. {
  1299. d_->code_name_ = code_name;
  1300. }
  1301. bool workbook::has_file_version() const
  1302. {
  1303. return d_->file_version_.is_set();
  1304. }
  1305. std::string workbook::app_name() const
  1306. {
  1307. return d_->file_version_.get().app_name;
  1308. }
  1309. std::size_t workbook::last_edited() const
  1310. {
  1311. return d_->file_version_.get().last_edited;
  1312. }
  1313. std::size_t workbook::lowest_edited() const
  1314. {
  1315. return d_->file_version_.get().lowest_edited;
  1316. }
  1317. std::size_t workbook::rup_build() const
  1318. {
  1319. return d_->file_version_.get().rup_build;
  1320. }
  1321. bool workbook::has_calculation_properties() const
  1322. {
  1323. return d_->calculation_properties_.is_set();
  1324. }
  1325. class calculation_properties workbook::calculation_properties() const
  1326. {
  1327. return d_->calculation_properties_.get();
  1328. }
  1329. void workbook::calculation_properties(const class calculation_properties &props)
  1330. {
  1331. d_->calculation_properties_ = props;
  1332. }
  1333. void workbook::garbage_collect_formulae()
  1334. {
  1335. auto any_with_formula = false;
  1336. for (auto ws : *this)
  1337. {
  1338. for (auto row : ws.rows(true))
  1339. {
  1340. for (auto cell : row)
  1341. {
  1342. if (cell.has_formula())
  1343. {
  1344. any_with_formula = true;
  1345. }
  1346. }
  1347. }
  1348. }
  1349. if (any_with_formula) return;
  1350. auto wb_rel = manifest().relationship(path("/"), relationship_type::office_document);
  1351. if (manifest().has_relationship(wb_rel.target().path(), relationship_type::calculation_chain))
  1352. {
  1353. auto calc_chain_rel = manifest().relationship(wb_rel.target().path(), relationship_type::calculation_chain);
  1354. auto calc_chain_part = manifest().canonicalize({wb_rel, calc_chain_rel});
  1355. manifest().unregister_override_type(calc_chain_part);
  1356. manifest().unregister_relationship(wb_rel.target(), calc_chain_rel.id());
  1357. }
  1358. }
  1359. void workbook::update_sheet_properties()
  1360. {
  1361. if (has_extended_property(xlnt::extended_property::titles_of_parts))
  1362. {
  1363. extended_property(xlnt::extended_property::titles_of_parts, sheet_titles());
  1364. }
  1365. if (has_extended_property(xlnt::extended_property::heading_pairs))
  1366. {
  1367. extended_property(xlnt::extended_property::heading_pairs,
  1368. std::vector<variant>{variant("Worksheets"), variant(static_cast<int>(sheet_count()))});
  1369. }
  1370. }
  1371. namespace {
  1372. // true if a sheet index is != worksheet relationship index
  1373. bool needs_reorder(const std::unordered_map<std::string, std::string> &title_to_rels,
  1374. const std::vector<std::string> &titles,
  1375. std::vector<std::string> &relation_ids)
  1376. {
  1377. bool all_match = true;
  1378. for (std::size_t title_index = 0; title_index < titles.size(); ++title_index)
  1379. {
  1380. const auto &rel = title_to_rels.at(titles[title_index]);
  1381. relation_ids.push_back(rel);
  1382. const auto expected_rel_id = "rId" + std::to_string(title_index + 1);
  1383. if (rel != expected_rel_id)
  1384. {
  1385. all_match = false;
  1386. }
  1387. }
  1388. return !all_match; // if all are as expected, reorder not required
  1389. };
  1390. struct rel_id_sorter
  1391. {
  1392. // true if lhs < rhs
  1393. bool operator()(const xlnt::relationship &lhs, const xlnt::relationship &rhs)
  1394. {
  1395. // format is rTd<decimal number 1..n>
  1396. if (lhs.id().size() != rhs.id().size()) // a number with more digits will be larger
  1397. {
  1398. return lhs.id().size() < rhs.id().size();
  1399. }
  1400. return lhs.id() < rhs.id();
  1401. }
  1402. };
  1403. } // namespace
  1404. void workbook::reorder_relationships()
  1405. {
  1406. const auto titles = sheet_titles();
  1407. // the relation ID corresponding to the title at the same index is copied into here
  1408. std::vector<std::string> worksheet_rel_ids;
  1409. worksheet_rel_ids.reserve(titles.size());
  1410. if (!needs_reorder(d_->sheet_title_rel_id_map_, titles, worksheet_rel_ids))
  1411. {
  1412. return;
  1413. }
  1414. // copy of existing relations
  1415. const auto wb_rel_target = manifest().relationship(path("/"), relationship_type::office_document).target();
  1416. auto rel_copy = manifest().relationships(wb_rel_target.path());
  1417. std::sort(rel_copy.begin(), rel_copy.end(), rel_id_sorter{});
  1418. // clear existing relations
  1419. for (const auto &rel : rel_copy)
  1420. {
  1421. manifest().unregister_relationship(wb_rel_target, rel.id());
  1422. }
  1423. // create new relations
  1424. std::size_t index = 0;
  1425. auto new_id = [&index]() { return "rId" + std::to_string(++index); }; // ids start from 1
  1426. // worksheets first
  1427. while (index < worksheet_rel_ids.size())
  1428. {
  1429. auto rel_it = std::find_if(rel_copy.begin(), rel_copy.end(),
  1430. [&](const relationship &rel) { return rel.id() == worksheet_rel_ids[index]; });
  1431. std::string rel_id = new_id();
  1432. d_->sheet_title_rel_id_map_.at(titles[index - 1]) = rel_id; // update title -> relation mapping
  1433. manifest().register_relationship(relationship(rel_id, rel_it->type(),
  1434. rel_it->source(), rel_it->target(), rel_it->target_mode()));
  1435. }
  1436. // then all the other relations in the same order they started (just new indices)
  1437. for (const auto &old_rel : rel_copy)
  1438. {
  1439. if (old_rel.type() == relationship_type::worksheet)
  1440. {
  1441. continue;
  1442. }
  1443. manifest().register_relationship(relationship(new_id(), old_rel.type(),
  1444. old_rel.source(), old_rel.target(), old_rel.target_mode()));
  1445. }
  1446. }
  1447. } // namespace xlnt