You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

XLS2CSVmra.java 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.hssf.eventusermodel.examples;
  16. import java.io.FileInputStream;
  17. import java.io.FileNotFoundException;
  18. import java.io.IOException;
  19. import java.io.PrintStream;
  20. import java.util.ArrayList;
  21. import java.util.List;
  22. import org.apache.poi.hssf.eventusermodel.EventWorkbookBuilder.SheetRecordCollectingListener;
  23. import org.apache.poi.hssf.eventusermodel.FormatTrackingHSSFListener;
  24. import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;
  25. import org.apache.poi.hssf.eventusermodel.HSSFListener;
  26. import org.apache.poi.hssf.eventusermodel.HSSFRequest;
  27. import org.apache.poi.hssf.eventusermodel.MissingRecordAwareHSSFListener;
  28. import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord;
  29. import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord;
  30. import org.apache.poi.hssf.model.HSSFFormulaParser;
  31. import org.apache.poi.hssf.record.BOFRecord;
  32. import org.apache.poi.hssf.record.BlankRecord;
  33. import org.apache.poi.hssf.record.BoolErrRecord;
  34. import org.apache.poi.hssf.record.BoundSheetRecord;
  35. import org.apache.poi.hssf.record.FormulaRecord;
  36. import org.apache.poi.hssf.record.LabelRecord;
  37. import org.apache.poi.hssf.record.LabelSSTRecord;
  38. import org.apache.poi.hssf.record.NoteRecord;
  39. import org.apache.poi.hssf.record.NumberRecord;
  40. import org.apache.poi.hssf.record.RKRecord;
  41. import org.apache.poi.hssf.record.SSTRecord;
  42. import org.apache.poi.hssf.record.StringRecord;
  43. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  44. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  45. /**
  46. * A XLS -> CSV processor, that uses the MissingRecordAware
  47. * EventModel code to ensure it outputs all columns and rows.
  48. * @author Nick Burch
  49. */
  50. @SuppressWarnings({"java:S106","java:S4823"})
  51. public class XLS2CSVmra implements HSSFListener {
  52. private int minColumns;
  53. private POIFSFileSystem fs;
  54. private PrintStream output;
  55. private int lastRowNumber;
  56. private int lastColumnNumber;
  57. /** Should we output the formula, or the value it has? */
  58. private boolean outputFormulaValues = true;
  59. /** For parsing Formulas */
  60. private SheetRecordCollectingListener workbookBuildingListener;
  61. private HSSFWorkbook stubWorkbook;
  62. // Records we pick up as we process
  63. private SSTRecord sstRecord;
  64. private FormatTrackingHSSFListener formatListener;
  65. /** So we known which sheet we're on */
  66. private int sheetIndex = -1;
  67. private BoundSheetRecord[] orderedBSRs;
  68. private List<BoundSheetRecord> boundSheetRecords = new ArrayList<>();
  69. // For handling formulas with string results
  70. private int nextRow;
  71. private int nextColumn;
  72. private boolean outputNextStringRecord;
  73. /**
  74. * Creates a new XLS -> CSV converter
  75. * @param fs The POIFSFileSystem to process
  76. * @param output The PrintStream to output the CSV to
  77. * @param minColumns The minimum number of columns to output, or -1 for no minimum
  78. */
  79. public XLS2CSVmra(POIFSFileSystem fs, PrintStream output, int minColumns) {
  80. this.fs = fs;
  81. this.output = output;
  82. this.minColumns = minColumns;
  83. }
  84. /**
  85. * Creates a new XLS -> CSV converter
  86. * @param filename The file to process
  87. * @param minColumns The minimum number of columns to output, or -1 for no minimum
  88. */
  89. public XLS2CSVmra(String filename, int minColumns) throws IOException, FileNotFoundException {
  90. this(
  91. new POIFSFileSystem(new FileInputStream(filename)),
  92. System.out, minColumns
  93. );
  94. }
  95. /**
  96. * Initiates the processing of the XLS file to CSV
  97. */
  98. public void process() throws IOException {
  99. MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(this);
  100. formatListener = new FormatTrackingHSSFListener(listener);
  101. HSSFEventFactory factory = new HSSFEventFactory();
  102. HSSFRequest request = new HSSFRequest();
  103. if(outputFormulaValues) {
  104. request.addListenerForAllRecords(formatListener);
  105. } else {
  106. workbookBuildingListener = new SheetRecordCollectingListener(formatListener);
  107. request.addListenerForAllRecords(workbookBuildingListener);
  108. }
  109. factory.processWorkbookEvents(request, fs);
  110. }
  111. /**
  112. * Main HSSFListener method, processes events, and outputs the
  113. * CSV as the file is processed.
  114. */
  115. @Override
  116. public void processRecord(org.apache.poi.hssf.record.Record record) {
  117. int thisRow = -1;
  118. int thisColumn = -1;
  119. String thisStr = null;
  120. switch (record.getSid())
  121. {
  122. case BoundSheetRecord.sid:
  123. boundSheetRecords.add((BoundSheetRecord)record);
  124. break;
  125. case BOFRecord.sid:
  126. BOFRecord br = (BOFRecord)record;
  127. if(br.getType() == BOFRecord.TYPE_WORKSHEET) {
  128. // Create sub workbook if required
  129. if(workbookBuildingListener != null && stubWorkbook == null) {
  130. stubWorkbook = workbookBuildingListener.getStubHSSFWorkbook();
  131. }
  132. // Output the worksheet name
  133. // Works by ordering the BSRs by the location of
  134. // their BOFRecords, and then knowing that we
  135. // process BOFRecords in byte offset order
  136. sheetIndex++;
  137. if(orderedBSRs == null) {
  138. orderedBSRs = BoundSheetRecord.orderByBofPosition(boundSheetRecords);
  139. }
  140. output.println();
  141. output.println(
  142. orderedBSRs[sheetIndex].getSheetname() +
  143. " [" + (sheetIndex+1) + "]:"
  144. );
  145. }
  146. break;
  147. case SSTRecord.sid:
  148. sstRecord = (SSTRecord) record;
  149. break;
  150. case BlankRecord.sid:
  151. BlankRecord brec = (BlankRecord) record;
  152. thisRow = brec.getRow();
  153. thisColumn = brec.getColumn();
  154. thisStr = "";
  155. break;
  156. case BoolErrRecord.sid:
  157. BoolErrRecord berec = (BoolErrRecord) record;
  158. thisRow = berec.getRow();
  159. thisColumn = berec.getColumn();
  160. thisStr = "";
  161. break;
  162. case FormulaRecord.sid:
  163. FormulaRecord frec = (FormulaRecord) record;
  164. thisRow = frec.getRow();
  165. thisColumn = frec.getColumn();
  166. if(outputFormulaValues) {
  167. if(Double.isNaN( frec.getValue() )) {
  168. // Formula result is a string
  169. // This is stored in the next record
  170. outputNextStringRecord = true;
  171. nextRow = frec.getRow();
  172. nextColumn = frec.getColumn();
  173. } else {
  174. thisStr = formatListener.formatNumberDateCell(frec);
  175. }
  176. } else {
  177. thisStr = '"' +
  178. HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression()) + '"';
  179. }
  180. break;
  181. case StringRecord.sid:
  182. if(outputNextStringRecord) {
  183. // String for formula
  184. StringRecord srec = (StringRecord)record;
  185. thisStr = srec.getString();
  186. thisRow = nextRow;
  187. thisColumn = nextColumn;
  188. outputNextStringRecord = false;
  189. }
  190. break;
  191. case LabelRecord.sid:
  192. LabelRecord lrec = (LabelRecord) record;
  193. thisRow = lrec.getRow();
  194. thisColumn = lrec.getColumn();
  195. thisStr = '"' + lrec.getValue() + '"';
  196. break;
  197. case LabelSSTRecord.sid:
  198. LabelSSTRecord lsrec = (LabelSSTRecord) record;
  199. thisRow = lsrec.getRow();
  200. thisColumn = lsrec.getColumn();
  201. if(sstRecord == null) {
  202. thisStr = '"' + "(No SST Record, can't identify string)" + '"';
  203. } else {
  204. thisStr = '"' + sstRecord.getString(lsrec.getSSTIndex()).toString() + '"';
  205. }
  206. break;
  207. case NoteRecord.sid:
  208. NoteRecord nrec = (NoteRecord) record;
  209. thisRow = nrec.getRow();
  210. thisColumn = nrec.getColumn();
  211. // TODO: Find object to match nrec.getShapeId()
  212. thisStr = '"' + "(TODO)" + '"';
  213. break;
  214. case NumberRecord.sid:
  215. NumberRecord numrec = (NumberRecord) record;
  216. thisRow = numrec.getRow();
  217. thisColumn = numrec.getColumn();
  218. // Format
  219. thisStr = formatListener.formatNumberDateCell(numrec);
  220. break;
  221. case RKRecord.sid:
  222. RKRecord rkrec = (RKRecord) record;
  223. thisRow = rkrec.getRow();
  224. thisColumn = rkrec.getColumn();
  225. thisStr = '"' + "(TODO)" + '"';
  226. break;
  227. default:
  228. break;
  229. }
  230. // Handle new row
  231. if(thisRow != -1 && thisRow != lastRowNumber) {
  232. lastColumnNumber = -1;
  233. }
  234. // Handle missing column
  235. if(record instanceof MissingCellDummyRecord) {
  236. MissingCellDummyRecord mc = (MissingCellDummyRecord)record;
  237. thisRow = mc.getRow();
  238. thisColumn = mc.getColumn();
  239. thisStr = "";
  240. }
  241. // If we got something to print out, do so
  242. if(thisStr != null) {
  243. if(thisColumn > 0) {
  244. output.print(',');
  245. }
  246. output.print(thisStr);
  247. }
  248. // Update column and row count
  249. if(thisRow > -1)
  250. lastRowNumber = thisRow;
  251. if(thisColumn > -1)
  252. lastColumnNumber = thisColumn;
  253. // Handle end of row
  254. if(record instanceof LastCellOfRowDummyRecord) {
  255. // Print out any missing commas if needed
  256. if(minColumns > 0) {
  257. // Columns are 0 based
  258. if(lastColumnNumber == -1) { lastColumnNumber = 0; }
  259. for(int i=lastColumnNumber; i<(minColumns); i++) {
  260. output.print(',');
  261. }
  262. }
  263. // We're onto a new row
  264. lastColumnNumber = -1;
  265. // End the row
  266. output.println();
  267. }
  268. }
  269. public static void main(String[] args) throws Exception {
  270. if(args.length < 1) {
  271. System.err.println("Use:");
  272. System.err.println(" XLS2CSVmra <xls file> [min columns]");
  273. System.exit(1);
  274. }
  275. int minColumns = -1;
  276. if(args.length >= 2) {
  277. minColumns = Integer.parseInt(args[1]);
  278. }
  279. XLS2CSVmra xls2csv = new XLS2CSVmra(args[0], minColumns);
  280. xls2csv.process();
  281. }
  282. }