public String getHtmlValue(Cell cell) { if (Cell.CELL_TYPE_BOOLEAN == cell.getCellType() || Cell.CELL_TYPE_NUMERIC == cell.getCellType()) { cell.setCellType(Cell.CELL_TYPE_STRING); return cell.getStringCellValue(); } else if (Cell.CELL_TYPE_STRING == cell.getCellType()) { if (cell.getRichStringCellValue().numFormattingRuns() == 0) { return XmlEscapers.xmlContentEscaper().escape(cell.getStringCellValue()); } else if (is07) { return getXSSFRichString((XSSFRichTextString) cell.getRichStringCellValue()); } else { return getHSSFRichString((HSSFRichTextString) cell.getRichStringCellValue()); } } return ""; }
/** * 07版本复杂数据 * @param rich * @return */ private String getXSSFRichString(XSSFRichTextString rich) { int nums = rich.numFormattingRuns(); StringBuilder sb = new StringBuilder(); String text = rich.toString(); int currentIndex = 0, lastIndex = 0; for (int i = 1; i <= nums; i++) { sb.append("<span "); try { sb.append("class='font_" + getFontIndex(rich.getFontOfFormattingRun(i - 1))); sb.append("_"); sb.append(cssRandom); sb.append("'"); } catch (Exception e) { } sb.append(">"); currentIndex = rich.getIndexOfFormattingRun(i) == -1 ? text.length() : rich.getIndexOfFormattingRun(i); sb.append( XmlEscapers.xmlContentEscaper().escape(text.substring(lastIndex, currentIndex))); sb.append("</span>"); lastIndex = currentIndex; } return sb.toString(); }
/** * 07版本复杂数据 * @param rich * @return */ private String getXSSFRichString(XSSFRichTextString rich) { int nums = rich.numFormattingRuns(); StringBuilder sb = new StringBuilder(); String text = rich.toString(); int currentIndex = 0, lastIndex = 0; for (int i = 1; i <= nums; i++) { sb.append("<span "); try { sb.append("class='font_" + getFontIndex(rich.getFontOfFormattingRun(i - 1))); sb.append("_"); sb.append(cssRandom); sb.append("'"); } catch (Exception e) { } sb.append(">"); currentIndex = rich.getIndexOfFormattingRun(i) == -1 ? text.length() : rich .getIndexOfFormattingRun(i); sb.append(XmlEscapers.xmlContentEscaper().escape( text.substring(lastIndex, currentIndex))); sb.append("</span>"); lastIndex = currentIndex; } return sb.toString(); }
/** * Tries to format the contents of the last contents appropriately based on the type of cell and the discovered * numeric format. * * @return */ String formattedContents() { switch (currentCell.getType()) { case "s": // string stored in shared table int idx = Integer.parseInt(lastContents); return new XSSFRichTextString(sst.getEntryAt(idx)).toString(); case "inlineStr": // inline string (not in sst) return new XSSFRichTextString(lastContents).toString(); case "str": // return lastContents; case "e": // error type return StringUtils.EMPTY;// "ERROR: " + lastContents; case "n": // numeric type if (currentCell.getNumericFormat() != null && lastContents.length() > 0) { return dataFormatter.formatRawCellContents(Double.parseDouble(lastContents), currentCell.getNumericFormatIndex(), currentCell.getNumericFormat()); } else { return lastContents; } default: return lastContents; } }
/** * Gets the font index of the <code>Font</code> in use at the specified * position in the given <code>RichTextString</code>. * @param richTextString The <code>RichTextString</code>. * @param fmtIndex The 0-based index of the formatting run. * @return The font index: If HSSF, a <code>short</code>. If XSSF, an * <code>XSSFFont</code>. */ public static Object getFontAtIndex(RichTextString richTextString, int fmtIndex) { if (richTextString instanceof HSSFRichTextString) { // Returns a short. return ((HSSFRichTextString) richTextString).getFontAtIndex(fmtIndex); } else if (richTextString instanceof XSSFRichTextString) { try { // Instead of returning null, getFontAtIndex (eventually) throws a // NullPointerException. It extracts a "CTRElt" from an array, and // it extracts a "CTRPrElt" from the "CTRElt". The "CTRprElt" can // be null if there is no font at the formatting run. Then, when // creating a "CTFont", it calls a method on the null "CTRPrElt". // Return an XSSFFont. return ((XSSFRichTextString) richTextString).getFontAtIndex(fmtIndex); } catch (NullPointerException e) { // Detect this case and return null. if (DEBUG) System.err.println(" NullPointerException caught!"); return null; } } else throw new IllegalArgumentException("Unexpected RichTextString type: " + richTextString.getClass().getName() + ": " + richTextString.getString()); }
@SuppressWarnings("resource") @Test public void testAddRow() { Calendar cal = Calendar.getInstance(); Date date = new Date(); writer.addRow("def"); writer .addRow(null, true, cal, date, 1.1, new HSSFRichTextString("Hello!"), new XSSFRichTextString("World."), new HSSFWorkbook() .getCreationHelper().createHyperlink(HyperlinkType.URL), 123, "abc"); assertEquals("def", writer.getWorkbook().getSheetAt(0).rowIterator().next() .cellIterator().next().getStringCellValue()); WorkbookWriter.openXLSX().addRow(new HSSFRichTextString("Hello!"), new XSSFRichTextString("World.")); WorkbookWriter.openXLS().addRow(new HSSFRichTextString("Hello!"), new XSSFRichTextString("World.")); }
private void createHeader(Map<String, CellStyle> styles, XSSFSheet sheet, List<String> header) { final XSSFRow rowhead = sheet.createRow(0); int i = 0; for (String headerColumn : header) { rowhead.createCell(i).setCellValue(new XSSFRichTextString(headerColumn)); rowhead.getCell(i).setCellStyle(styles.get("header")); i++; } }
/** * Resolve the given value with respect to whether it is a reference to element in shared strings table. * Also decode the final value. * * @param value Value read in element. * @param lookupNextValueInSST Whether the value is an index into the shared strings table. * @return */ private String resolveValue(String value, boolean lookupNextValueInSST) { if(lookupNextValueInSST) { int idx = (int)Double.parseDouble(value); return new XSSFRichTextString(sst.getEntryAt(idx)).toString(); } return new XSSFRichTextString(value).toString(); }
public static void writeExcel(HttpServletResponse response,List<String> list) throws Exception { response.setContentType("application/vnd.ms-excel");//文件格式,此处设置为excel response.setHeader("Content-Disposition","attachment;filename=file.xls");//此处设置了下载文件的默认名称 ServletOutputStream sos = response.getOutputStream(); //创建一个新的excel XSSFWorkbook wb = new XSSFWorkbook();//XSSFWorkbook /** * 采用现成Excel模板 * 用这种方式得先保证每个cell有值,不然会报空指针 * 有时我们用row.getCell(i)会得到null,那么此时就要用Iterator<Cell> it = row.cellIterator(); * XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(new File("D://a.xlsx"))); * XSSFSheet sheet = wb.getSheet("Sheet1"); * row[i] = sheet.getRow(i); * headerCell[j] = row[i].getCell(j); */ //创建sheet页 XSSFSheet sheet = wb.createSheet("sheet1");//sheet名 //创建行数 XSSFRow[] row = new XSSFRow[list.size()]; //插入数据 for (int i = 0; i < row.length; i++) { row[i] = sheet.createRow(i); sheet.setDefaultColumnWidth(30);//设置列的长度 String info[] = list.get(i).split(","); XSSFCell[] headerCell = new XSSFCell[info.length]; for (int j = 0; j < headerCell.length; j++) { headerCell[j] = row[i].createCell(j); headerCell[j].setCellValue(new XSSFRichTextString(info[j])); /**设置模板样式*/ //headerCell[j].setCellStyle(setStyle(wb)); } } wb.write(sos); wb.close(); sos.flush(); sos.close(); response.flushBuffer(); }
private Font getFontForFormattingRun(RichTextString richText, int i) { if (richText instanceof HSSFRichTextString) { HSSFRichTextString hssfRichText = (HSSFRichTextString) richText; return ((PoiWorkbook.PoiHssfWorkbook) getWorkbook()).getFont(hssfRichText.getFontOfFormattingRun(i)).getFont(); } else { return getWorkbook().getFont(((XSSFRichTextString) richText).getFontOfFormattingRun(i)).getFont(); } }
@Override public void handleInlineString(XSSFCellStyle style, String inlineString) { XSSFRichTextString rtsi = new XSSFRichTextString(inlineString); rawValues.add(rtsi.toString().toUpperCase()); formattedValues.add('"' + rtsi.toString() + '"'); }
@Override public void handleSharedStringsTableIndex(XSSFCellStyle style, String sharedStringsTableIndex) { try { int idx = Integer.parseInt(sharedStringsTableIndex); XSSFRichTextString rtss = new XSSFRichTextString(sharedStringsTable.getEntryAt(idx)); rawValues.add(rtss.toString()); formattedValues.add('"' + rtss.toString() + '"'); } catch (NumberFormatException ex) { rawValues.add("ERROR"); formattedValues.add("ERROR"); } }
public void writeCoverSheet(String projectName,String creatorName, String creatorEmail,String organizationName,String toolInfo) { sheet.getRow(ROW_10).getCell(COL_D).setCellValue( new XSSFRichTextString(projectName)); sheet.getRow(ROW_10).getCell(COL_F).setCellValue( new XSSFRichTextString(DateUtil.getCurrentTime("%1$tY-%1$tm-%1$te (%1$ta)"))); sheet.getRow(ROW_11).getCell(COL_D).setCellValue( new XSSFRichTextString(creatorEmail)); sheet.getRow(ROW_12).getCell(COL_D).setCellValue( new XSSFRichTextString(organizationName)); sheet.getRow(ROW_13).getCell(COL_D).setCellValue( new XSSFRichTextString(toolInfo)); }
/** * (non-Javadoc) * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String) */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { // 处理excel的行 if ("row".equals(qName)) { if (cacheSize > rowCache.size() && cRow.getCells() != null) { rowCache.add(cRow); } else { rowsHandler.handleRows(rowCache); rowCache.clear(); } lastElementName = null; if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.worked(1); } else if ("t".equals(qName) && !isSheredString) { cCell.setCellConentent(lastCellContent.toString().trim()); lastCellContent.delete(0, lastCellContent.length()); } else if ("v".equals(qName)) { int idx = -1; try { idx = Integer.parseInt(lastCellContent.toString().trim()); XSSFRichTextString rtss = new XSSFRichTextString(sharedStringsTable.getEntryAt(idx)); cCell.setCellConentent(rtss.toString()); lastCellContent.delete(0, lastCellContent.length()); } catch (NumberFormatException e) { } } }
/** * Returns the contents of the cell, with no formatting applied * * @return */ String unformattedContents() { switch (currentCell.getType()) { case "s": // string stored in shared table int idx = Integer.parseInt(lastContents); return new XSSFRichTextString(sst.getEntryAt(idx)).toString(); case "inlineStr": // inline string (not in sst) return new XSSFRichTextString(lastContents).toString(); default: return lastContents; } }
/** * Returns the contents of the cell, with no formatting applied * * @return */ String unformattedContents() { switch(currentCell.getType()) { case "s": //string stored in shared table if (!lastContents.isEmpty()) { int idx = Integer.parseInt(lastContents); return new XSSFRichTextString(sst.getEntryAt(idx)).toString(); } return lastContents; case "inlineStr": //inline string (not in sst) return new XSSFRichTextString(lastContents).toString(); default: return lastContents; } }
/** * Format a <code>RichTextString</code> that has already been created. * @param string A <code>RichTextString</code>. * @param numFormattingRuns The number of formatting runs. * @param formattingRuns A <code>List</code> of <code>FormattingRuns</code>. */ public static void formatString(RichTextString string, int numFormattingRuns, List<FormattingRun> formattingRuns) { // Apply the formatting runs. for (int i = 0; i < numFormattingRuns; i++) { FormattingRun run = formattingRuns.get(i); int begin = run.getBegin(); int end = begin + run.getLength(); Object font = run.getFont(); if (DEBUG) { System.err.println(" RTSU.cFS: Applying format (" + i + "): begin=" + begin + ", length=" + run.getLength() + ", font=" + font + " to string \"" + string.getString() + "\"."); } if (string instanceof HSSFRichTextString) string.applyFont(begin, end, (Short) font); else if (string instanceof XSSFRichTextString) { if (font != null) string.applyFont(begin, end, (XSSFFont) font); } else throw new IllegalArgumentException("Unexpected RichTextString type: " + string.getClass().getName() + ": " + string.getString()); } }
/** * Gets the font index of the specified formatting run in the given * <code>RichTextString</code>. * @param richTextString The <code>RichTextString</code>. * @param fmtIndex The 0-based index of the formatting run. * @return The font index. If HSSF, a <code>short</code>. If XSSF, an * <code>XSSFFont</code>. */ private static Object getFontOfFormattingRun(RichTextString richTextString, int fmtIndex) { if (richTextString instanceof HSSFRichTextString) { return ((HSSFRichTextString) richTextString).getFontOfFormattingRun(fmtIndex); } else if (richTextString instanceof XSSFRichTextString) { try { // Instead of returning null, getFontOfFormattingRun (eventually) // throws a NullPointerException. It extracts a "CTRElt" from an // array, and it extracts a "CTRPrElt" from the "CTRElt". The // "CTRprElt" can be null if there is no font at the formatting // run. Then, when creating a "CTFont", it calls a method on the // null "CTRPrElt". // Return the XSSFFont. return ((XSSFRichTextString) richTextString).getFontOfFormattingRun(fmtIndex); } catch (NullPointerException e) { // Detect this case and return null. if (DEBUG) System.err.println(" NullPointerException caught!"); return null; } } else throw new IllegalArgumentException("Unexpected RichTextString type: " + richTextString.getClass().getName() + ": " + richTextString.getString()); }
public void endElement(String uri, String localName, String name) throws SAXException { // 根据SST的索引值的到单元格的真正要存储的字符串 // 这时characters()方法可能会被调用多次 if (nextIsString) { try { int idx = Integer.parseInt(lastContents); lastContents = new XSSFRichTextString(sst.getEntryAt(idx)) .toString(); } catch (Exception e) { } } // v => 单元格的值,如果单元格是字符串则v标签的值为该字符串在SST中的索引 // 将单元格内容加入rowlist中,在这之前先去掉字符串前后的空白符 if (name.equals("v")) { String value = lastContents.trim(); value = value.equals("") ? " " : value; rowlist.add(curCol, value); curCol++; } else { // 如果标签名称为 row ,这说明已到行尾,调用 optRows() 方法 if (name.equals("row") && curCol>0) { optRow(sheetIndex, curRow, rowlist); rowlist.clear(); curRow++; curCol = 0; } } }
@Override public void addHeaderField(final String fieldName) throws IOException { final Cell cell = this.row.createCell(this.colCount++); cell.setCellValue(new XSSFRichTextString(fieldName)); cell.setCellStyle(this.headerStyle); }
@Override public void writeText(final String text) throws IOException { final Cell cell = this.row.createCell(this.colCount++); if (text != null) { cell.setCellValue(new XSSFRichTextString(text)); cell.setCellStyle(this.defaultStyle); } }
/** * Adds a row to the sheet. * * @param fields * an Iterable of Object * @return this {@link WorkbookWriter} */ public WorkbookWriter addRow(@NonNull Iterable<? extends Object> fields) { Row row; if (sheet.getLastRowNum() == 0 && sheet.getPhysicalNumberOfRows() == 0) row = sheet.createRow(0); else row = sheet.createRow(sheet.getLastRowNum() + 1); int i = 0; for (Object o : fields) { Cell cell = row.createCell(i); if (o != null) { if (o instanceof Boolean) cell.setCellValue((Boolean) o); else if (o instanceof Calendar) cell.setCellValue((Calendar) o); else if (o instanceof Date) cell.setCellValue((Date) o); else if (o instanceof Double) cell.setCellValue((Double) o); else if (o instanceof RichTextString) if ((o instanceof HSSFRichTextString && workbook instanceof HSSFWorkbook) || (o instanceof XSSFRichTextString && workbook instanceof XSSFWorkbook)) { cell.setCellValue((RichTextString) o); } else { cell.setCellValue(o.toString()); } else if (o instanceof Hyperlink) cell.setHyperlink((Hyperlink) o); else if (o instanceof Number) cell.setCellValue(((Number) o).doubleValue()); else cell.setCellValue(o.toString()); } i++; } return this; }
public void endElement(String uri, String localName, String name) throws SAXException { // Process the last contents as required. // Do now, as characters() may be called more than once if (nextIsString) { int idx = Integer.parseInt(value); value = new XSSFRichTextString(sst.getEntryAt(idx)).toString(); nextIsString = false; } // v => contents of a cell // Output after we've seen the string contents if (name.equals("v")) { if (lineIndex == skip) { if (value == null || value.trim().isEmpty()) value = "column" + columnIndex; headers.add(value); } else { if (columnIndex < headers.size()) { String key = headers.get(columnIndex); data.put(key, value); } else { data.put("column" + columnIndex, value); } } columnIndex++; } }
/** * 初始化函数 * @param title 表格标题,传“空值”,表示无标题 * @param headerList 表头列表 */ private void initialize(String title, List<String> headerList) { this.wb = new SXSSFWorkbook(500); this.sheet = wb.createSheet("Export"); this.styles = createStyles(wb); // Create title if (StringUtils.isNotBlank(title)){ Row titleRow = sheet.createRow(rownum++); titleRow.setHeightInPoints(30); Cell titleCell = titleRow.createCell(0); titleCell.setCellStyle(styles.get("title")); titleCell.setCellValue(title); sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), titleRow.getRowNum(), headerList.size()-1)); } // Create header if (headerList == null){ throw new RuntimeException("headerList not null!"); } Row headerRow = sheet.createRow(rownum++); headerRow.setHeightInPoints(16); for (int i = 0; i < headerList.size(); i++) { Cell cell = headerRow.createCell(i); cell.setCellStyle(styles.get("header")); String[] ss = StringUtils.split(headerList.get(i), "**", 2); if (ss.length==2){ cell.setCellValue(ss[0]); Comment comment = this.sheet.createDrawingPatriarch().createCellComment( new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6)); comment.setString(new XSSFRichTextString(ss[1])); cell.setCellComment(comment); }else{ cell.setCellValue(headerList.get(i)); } sheet.autoSizeColumn(i); } for (int i = 0; i < headerList.size(); i++) { int colWidth = sheet.getColumnWidth(i)*2; sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth); } log.debug("Initialize success."); }
/** * 对解析出来的数据进行类型处理 * * @param value * 单元格的值(这时候是一串数字) * @param newValue * 一个空字符串 * @return string */ public String getDataValue(String value, String newValue) { switch (mNextDataType) { // 这几个的顺序不能随便交换,交换了很可能会导致数据错误 case BOOL: char first = value.charAt(0); newValue = first == '0' ? "FALSE" : "TRUE"; break; case ERROR: newValue = "\"ERROR:" + value.toString() + '"'; break; case FORMULA: newValue = '"' + value.toString() + '"'; break; case INLINESTR: newValue = new XSSFRichTextString(value.toString()).toString(); break; case STRING: newValue = String.valueOf(value); break; case NUMBER: if (mFormatString != null) { try { newValue = mFormatter.formatRawCellContents(Double.parseDouble(value), mFormatIndex, mFormatString).trim(); } catch (NumberFormatException e) { newValue = mEmptyCellValue; } } else { newValue = value; } newValue = newValue != null ? newValue.replace("_", "").trim() : null; break; case DATE: // TODO:对日期字符串作特殊处理 newValue = mFormatter.formatRawCellContents(Double.parseDouble(value), mFormatIndex, mFormatString); newValue = newValue.replace(" ", "T"); break; default: newValue = mEmptyCellValue; break; } return newValue; }
/** * 初始化函数 * * @param title 表格标题,传“空值”,表示无标题 * @param headerList 表头列表 */ private void initialize(String title, List<String> headerList) { this.wb = new SXSSFWorkbook(500); this.sheet = wb.createSheet("Export"); this.styles = createStyles(wb); // Create title if (StringUtils.isNotBlank(title)) { Row titleRow = sheet.createRow(rownum++); titleRow.setHeightInPoints(30); Cell titleCell = titleRow.createCell(0); titleCell.setCellStyle(styles.get("title")); titleCell.setCellValue(title); sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), titleRow.getRowNum(), headerList.size() - 1)); } // Create header if (headerList == null) { throw new RuntimeException("headerList not null!"); } Row headerRow = sheet.createRow(rownum++); headerRow.setHeightInPoints(16); for (int i = 0; i < headerList.size(); i++) { Cell cell = headerRow.createCell(i); cell.setCellStyle(styles.get("header")); String[] ss = StringUtils.split(headerList.get(i), "**", 2); if (ss.length == 2) { cell.setCellValue(ss[0]); Comment comment = this.sheet.createDrawingPatriarch().createCellComment( new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6)); comment.setString(new XSSFRichTextString(ss[1])); cell.setCellComment(comment); } else { cell.setCellValue(headerList.get(i)); } // sheet.autoSizeColumn(i); } for (int i = 0; i < headerList.size(); i++) { int colWidth = sheet.getColumnWidth(i) * 2; sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth); } log.debug("Initialize success."); }
/** * 初始化函数 * * @param title 表格标题,传“空值”,表示无标题 * @param headerList 表头列表 */ private void initialize(String title, List<String> headerList) { this.wb = new SXSSFWorkbook(500); this.sheet = wb.createSheet("Export"); this.styles = createStyles(wb); // Create title if (StringUtils.isNotBlank(title)) { Row titleRow = sheet.createRow(rownum++); titleRow.setHeightInPoints(30); Cell titleCell = titleRow.createCell(0); titleCell.setCellStyle(styles.get("title")); titleCell.setCellValue(title); sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), titleRow.getRowNum(), headerList.size() - 1)); } // Create header if (headerList == null) { throw new RuntimeException("headerList not null!"); } Row headerRow = sheet.createRow(rownum++); headerRow.setHeightInPoints(16); for (int i = 0; i < headerList.size(); i++) { Cell cell = headerRow.createCell(i); cell.setCellStyle(styles.get("header")); String[] ss = StringUtils.split(headerList.get(i), "**", 2); if (ss.length == 2) { cell.setCellValue(ss[0]); Comment comment = this.sheet.createDrawingPatriarch().createCellComment( new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6)); comment.setString(new XSSFRichTextString(ss[1])); cell.setCellComment(comment); } else { cell.setCellValue(headerList.get(i)); } sheet.autoSizeColumn(i); } for (int i = 0; i < headerList.size(); i++) { int colWidth = sheet.getColumnWidth(i) * 2; sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth); } log.debug("Initialize success."); }
/** * 初始化函数 * * @param title 表格标题,传“空值”,表示无标题 * @param headerList 表头列表 */ private void initialize(String title, List<String> headerList) { this.wb = new SXSSFWorkbook(500); this.sheet = wb.createSheet("Export"); this.styles = createStyles(wb); // Create title if (StringUtils.isNotBlank(title)) { Row titleRow = sheet.createRow(rownum++); titleRow.setHeightInPoints(30); Cell titleCell = titleRow.createCell(0); titleCell.setCellStyle(styles.get("title")); titleCell.setCellValue(title); sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), titleRow.getRowNum(), headerList.size() - 1)); } // Create header if (headerList == null) { throw new RuntimeException("headerList not null!"); } Row headerRow = sheet.createRow(rownum++); headerRow.setHeightInPoints(16); for (int i = 0; i < headerList.size(); i++) { Cell cell = headerRow.createCell(i); cell.setCellStyle(styles.get("header")); String[] ss = StringUtils.split(headerList.get(i), "**", 2); if (ss.length == 2) { cell.setCellValue(ss[0]); Comment comment = this.sheet.createDrawingPatriarch() .createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6)); comment.setString(new XSSFRichTextString(ss[1])); cell.setCellComment(comment); } else { cell.setCellValue(headerList.get(i)); } sheet.autoSizeColumn(i); } for (int i = 0; i < headerList.size(); i++) { int colWidth = sheet.getColumnWidth(i) * 2; sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth); } log.debug("Initialize success."); }
@Override public void endElement(String uri, String localName, String name) throws SAXException { // 根据SST的索引值的到单元格的真正要存储的字符串 // 这时characters()方法可能会被调用多次 if (nextIsString) { try { int idx = Integer.parseInt(lastContents); lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString(); } catch (Exception e) { //e.printStackTrace(); } } // v => 单元格的值,如果单元格是字符串则v标签的值为该字符串在SST中的索引 // 将单元格内容加入rowlist中,在这之前先去掉字符串前后的空白符 if (name.equals("v")) { String value = lastContents.trim(); value = value.equals("") ? " " : value; rowlist.add(curCol, value); curCol++; closeV = true; } else { if (name.equals("c")) { if (!closeV) { rowlist.add(curCol, ""); curCol++; } } // 如果标签名称为 row ,这说明已到行尾,调用 optRows() 方法 if (name.equals("row")) { row = new XRow(); for (int i = 0; i < rowlist.size(); i++) { XCell cell = new XCell(); cell.setColumnIndex(i + 'A'); cell.setRowIndex(curRow + 1); cell.setValue((String) rowlist.get(i)); row.setRowIndex(curRow + 1); row.addCell(cell); } rowDataList.add(row); rowlist.clear(); curRow++; curCol = 0; } } }
@Override public XSSFRichTextString createRichTextString(String s) { return new XSSFRichTextString(s); }
/** * (non-Javadoc) * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String) */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { // 处理excel的行 if ("row".equals(qName)) { // 如果为第一行不添加到缓存中 if (cRow.getRowNumber() == 1) { if (!validateLangs(cRow)) { throw new SAXException("LANG-CODE-ERORR"); } if(isHasDuplicateLangCode()){ throw new SAXException("DUPLICATE-LANG-CODE-ERORR"); } if (!validateAppend()) { throw new SAXException("DIFF--SRC-LANG-CODE"); } tmxWriter.writeHeader(getSrcLang()); } else { if (cache_size > cache.size()) { if (cRow.getCells() != null) { cache.add(cRow.toTmxTu()); } } else { if (monitor.isCanceled()) { throw new SAXException(""); } writeTmxTU(cache, tmxWriter); monitor.worked(1); } } lastElementName = null; } if (!isSheredString) { if ("t".equals(qName)) { cCell.setCellConentent(lastCellContent.toString().trim()); cCell.setLangCode(langCodes.get(cCell.getCellNumber())); lastCellContent.delete(0, lastCellContent.length()); } } else { if ("v".equals(qName)) { int idx = -1; try { idx = Integer.parseInt(lastCellContent.toString().trim()); XSSFRichTextString rtss = new XSSFRichTextString(sharedStringsTable.getEntryAt(idx)); cCell.setCellConentent(rtss.toString()); cCell.setLangCode(langCodes.get(cCell.getCellNumber())); lastCellContent.delete(0, lastCellContent.length()); } catch (NumberFormatException e) { } } } }
/** * (non-Javadoc) * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String) */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { // 处理excel的行 if ("row".equals(qName)) { // 如果为第一行不添加到缓存中 if (cRow.getRowNumber() == 1) { if (!validateLangs(cRow)) { throw new SAXException("LANG-CODE-ERORR"); } if (isHasDuplicateLangCode()) { throw new SAXException("DUPLICATE-LANG-CODE-ERORR"); } if (!validateAppend()) { throw new SAXException("DIFF--SRC-LANG-CODE"); } String xmlDecl = TmxTemplet.genertateTmxXmlDeclar(); tmxWriter.writeXmlString(xmlDecl); TmxHeader header = TmxTemplet.generateTmxHeader(getSrcLang(), "unknown", "sentence", "Microsoft Excel", null, null, null); tmxWriter.writeXmlString("<tmx version=\"1.4\">\n"); tmxWriter.writeHeader(TmxTemplet.header2Xml(header)); tmxWriter.writeXmlString("<body>\n"); } else { if (cache_size > cache.size()) { if (cRow.getCells() != null) { cache.add(cRow.toTmxTu()); } } else { if (monitor.isCanceled()) { throw new SAXException(""); } writeTmxTU(cache, tmxWriter); monitor.worked(1); } } lastElementName = null; } if (!isSheredString) { if ("t".equals(qName)) { cCell.setCellConentent(lastCellContent.toString().trim()); cCell.setLangCode(langCodes.get(cCell.getCellNumber())); lastCellContent.delete(0, lastCellContent.length()); } } else { if ("v".equals(qName)) { int idx = -1; try { idx = Integer.parseInt(lastCellContent.toString().trim()); XSSFRichTextString rtss = new XSSFRichTextString(sharedStringsTable.getEntryAt(idx)); cCell.setCellConentent(rtss.toString()); cCell.setLangCode(langCodes.get(cCell.getCellNumber())); lastCellContent.delete(0, lastCellContent.length()); } catch (NumberFormatException e) { } } } }
@Override public RichTextString createRichTextString(String value) { XSSFRichTextString result = new XSSFRichTextString(value); return result; }
/** * Tries to format the contents of the last contents appropriately based on * the type of cell and the discovered numeric format. * * @return */ Supplier formattedContents() { switch(currentCell.getType()) { case "s": //string stored in shared table if (!lastContents.isEmpty()) { int idx = Integer.parseInt(lastContents); return new StringSupplier(new XSSFRichTextString(sst.getEntryAt(idx)).toString()); } return new StringSupplier(lastContents); case "inlineStr": //inline string (not in sst) return new StringSupplier(new XSSFRichTextString(lastContents).toString()); case "str": //forumla type return new StringSupplier('"' + lastContents + '"'); case "e": //error type return new StringSupplier("ERROR: " + lastContents); case "n": //numeric type if(currentCell.getNumericFormat() != null && lastContents.length() > 0) { // the formatRawCellContents operation incurs a significant overhead on large sheets, // and we want to defer the execution of this method until the value is actually needed. // it is not needed in all cases.. final String currentLastContents = lastContents; final int currentNumericFormatIndex = currentCell.getNumericFormatIndex(); final String currentNumericFormat = currentCell.getNumericFormat(); return new Supplier() { String cachedContent; @Override public Object getContent() { if (cachedContent == null) { cachedContent = dataFormatter.formatRawCellContents( Double.parseDouble(currentLastContents), currentNumericFormatIndex, currentNumericFormat); } return cachedContent; } }; } else { return new StringSupplier(lastContents); } default: return new StringSupplier(lastContents); } }
/** * Take the first <code>Font</code> from the given * <code>RichTextString</code> and apply it to the given <code>Cell's</code> * <code>CellStyle</code>. * @param cell The <code>Cell</code>. * @param richTextString The <code>RichTextString</code> that contains the * desired <code>Font</code>. * @since 0.2.0 */ public static void applyFont(RichTextString richTextString, Cell cell) { if (DEBUG) System.err.println("RTSU.aF: richTextString = " + richTextString + ", sheet " + cell.getSheet().getSheetName() + ", cell at row " + cell.getRowIndex() + ", col " + cell.getColumnIndex()); Font font; short fontIdx; if (richTextString == null) return; if (richTextString instanceof HSSFRichTextString) { fontIdx = ((HSSFRichTextString) richTextString).getFontAtIndex(0); font = cell.getSheet().getWorkbook().getFontAt(fontIdx); } else if (richTextString instanceof XSSFRichTextString) { try { // Instead of returning null, getFontAtIndex (eventually) throws a // NullPointerException. It extracts a "CTRElt" from an array, and // it extracts a "CTRPrElt" from the "CTRElt". The "CTRprElt" can // be null if there is no font at the formatting run. Then, when // creating a "CTFont", it calls a method on the null "CTRPrElt". font = ((XSSFRichTextString) richTextString).getFontAtIndex(0); } catch (NullPointerException e) { if (DEBUG) System.err.println(" NullPointerException caught!"); font = null; } } else { throw new IllegalArgumentException("Unexpected RichTextString type: " + richTextString.getClass().getName() + ": " + richTextString.getString()); } if (font != null) { if (DEBUG) { fontIdx = font.getIndex(); System.err.println(" Font is " + font.toString() + ", index " + fontIdx); } CellStyle cellStyle = cell.getCellStyle(); Workbook workbook = cell.getSheet().getWorkbook(); CellStyle newCellStyle = findCellStyle(workbook, cellStyle, font); if (newCellStyle == null) { newCellStyle = workbook.createCellStyle(); newCellStyle.cloneStyleFrom(cellStyle); // For some reason, just setting the Font directly doesn't work. //newCellStyle.setFont(font); Font foundFont = findFont(workbook, font); newCellStyle.setFont(foundFont); } cell.setCellStyle(newCellStyle); } }
private String createValue() { if (_value.length() == 0) { return null; } switch (_dataType) { case BOOL: char first = _value.charAt(0); return first == '0' ? "false" : "true"; case ERROR: logger.warn("Error-cell occurred: {}", _value); return _value.toString(); case FORMULA: return _value.toString(); case INLINESTR: XSSFRichTextString rtsi = new XSSFRichTextString(_value.toString()); return rtsi.toString(); case SSTINDEX: String sstIndex = _value.toString(); int idx = Integer.parseInt(sstIndex); XSSFRichTextString rtss = new XSSFRichTextString(_sharedStringTable.getEntryAt(idx)); return rtss.toString(); case NUMBER: final String numberString = _value.toString(); if (_formatString != null) { DataFormatter formatter = getDataFormatter(); if (HSSFDateUtil.isADateFormat(_formatIndex, _formatString)) { Date date = DateUtil.getJavaDate(Double.parseDouble(numberString)); return DateUtils.createDateFormat().format(date); } return formatter.formatRawCellContents(Double.parseDouble(numberString), _formatIndex, _formatString); } else { if (numberString.endsWith(".0")) { // xlsx only stores doubles, so integers get ".0" appended // to them return numberString.substring(0, numberString.length() - 2); } return numberString; } default: logger.error("Unsupported data type: {}", _dataType); return ""; } }
@Override public void endElement(String uri, String localName, String qualifiedName) throws SAXException { if (uri != null && ! uri.equals(NS_SPREADSHEETML)) { return; } String thisStr = null; // v => contents of a cell if (isTextTag(localName)) { valueIsOpen = false; // Process the value contents as required, now we have it all switch (nextDataType) { case BOOLEAN: char first = value.charAt(0); thisStr = first == '0' ? "F" : "T"; break; case ERROR: thisStr = "ERROR:" + value.toString(); break; case FORMULA: thisStr = value.toString(); break; case INLINE_STRING: // TODO: Can these ever have formatting on them? XSSFRichTextString rtsi = new XSSFRichTextString(value.toString()); thisStr = rtsi.toString(); break; case SST_STRING: String sstIndex = value.toString(); try { int idx = Integer.parseInt(sstIndex); XSSFRichTextString rtss = new XSSFRichTextString(sharedStringsTable.getEntryAt(idx)); thisStr = rtss.toString(); } catch (NumberFormatException ex) { logger.log(POILogger.ERROR, "Failed to parse SST index '" + sstIndex, ex); } break; case NUMBER: thisStr = value.toString(); break; default: thisStr = "(TODO: Unexpected type: " + nextDataType + ")"; break; } output.cell(column, thisStr, cellStyleStr); } else if ("is".equals(localName)) { isIsOpen = false; } else if ("row".equals(localName)) { // Finish up the row output.endRow(rowNum); // some sheets do not have rowNum set in the XML, Excel can read them so we should try to read them as well nextRowNum = rowNum + 1; } }