GcExcel vs Apache POI
Apache POI 在 Java 中解析、生成 Excel 是非常有名的組件,開發者會選擇 POI 來完成項目開發及需求。但是 POI 在內存消耗,性能以及 Excel 功能覆蓋上存在缺陷。
GrapeCity Documents for Excel(GcExcel)是一款基于 Java 平臺,支持批量創建、編輯、打印、導入/導出 Excel 文件的服務端表格組件,能夠高性能處理和高度兼容 Excel。該頁展示 GcExcel 了與 Apache POI 和第三方表格組件在功能和性能上的對比測試。
性能對比
對比維度 | GcExcel | POI | 對比結果 |
---|---|---|---|
文件打開
47MB 包含 1000萬 個單元格數據的 Excel 文件 |
6.2秒 | 63.07秒 | GcExcel 比 POI 大約快 10 倍 |
保存文件
保存包含 500 萬個單元格數據的 Excel 文件 |
15.294秒 | 45.816秒 | GcExcel 比 POI 大約快 3 倍 |
讀取單元格數據
讀取 1000 萬個完全不同的單元格數據 |
0.573秒 | 16.634秒 | GcExcel 比 POI 大約快 29 倍 |
設置單元格數據
設置 500 萬個完全不同的單元格數據 |
0.21秒 | 7.681秒 | GcExcel 比 POI 大約快 38 倍 |
更詳細的性能對比請參考:GcExcel與POI性能對比測試
功能對比
對比維度 | GcExcel | POI |
---|---|---|
公式數量 | 支持 482 種 Excel 計算公式 | Apache POI 中,支持的公式數量僅支持 216 種。
(根據WorkbookEvaluator.getSupportedFunctionNames();) |
導出 PDF | 支持導出 PDF 格式,包括頁面設置選項、PDF 安全選項和文檔屬性 | 不支持導出 PDF |
條件格式 | 支持與 Excel 相同的條件格式 | 僅支持基礎條件格式,更多的條件格式需要基于底層接口實現 |
圖表類型 | 支持 64 種圖表類型
除地圖之外,支持 Excel 版本支持的所有圖表類型 Excel支持的圖表類型 |
僅對條形圖、柱形圖、折線圖、雷達圖和散點圖提供有限的支持 |
切片器 | 支持表和透視表,同時提供樣式,且允許自定義切片器樣式 | 不支持切片器 |
更多對比內容:GcExcel與POI功能對比
簡單易上手
GcExcel作為成熟的組件庫,除了擁有完整的功能和特性之外,還有簡單易用的API
- 打開/保存Excel文件
- 將工作簿導出成CSV
- 創建worksheet
- 創建日期格式的單元格
- 獲取數據
// GcExcel 打開/保存Excel文件
// 創建一個workbook的對象
Workbook workbook = new Workbook();
// 打開file.xlsx文件
workbook.open("file.xlsx");
// 保存至Excel文件
workbook.save("newfile.xlsx");
// POI 打開/保存文件
File file = new File("Geeks.xlsx");
FileInputStream fip = new FileInputStream(file);
XSSFWorkbook workbook = new XSSFWorkbook(fip);
//...
try (OutputStream fileOut = new FileOutputStream("workbook.xlsx")) {
wb.write(fileOut);
}
// GcExcel 保存工作簿為CSV
Workbook workbook = new Workbook();
// 對workbook添加數據
workbook.save("SaveWorkbookToCsvFile.csv");
// POI 導出CSV
/**
\* A rudimentary XLSX -> CSV processor modeled on the
\* POI sample program XLS2CSVmra by Nick Burch from the
\* package org.apache.poi.hssf.eventusermodel.examples.
\* Unlike the HSSF version, this one completely ignores
\* missing rows.
\*
\* Data sheets are read using a SAX parser to keep the
\* memory footprint relatively small, so this should be
\* able to read enormous workbooks. The styles table and
\* the shared-string table must be kept in memory. The
\* standard POI styles table class is used, but a custom
\* (read-only) class is used for the shared string table
\* because the standard POI SharedStringsTable grows very
\* quickly with the number of unique strings.
\*
\* Thanks to Eric Smith for a patch that fixes a problem
\* triggered by cells with multiple "t" elements, which is
\* how Excel represents different formats (e.g., one word
\* plain and one word bold).
\*
\* @author Chris Lott
*/
public class ApacheXLSX2CSV {
/**
* The type of the data value is indicated by an attribute on the cell.
* The value is usually in a "v" element within the cell.
*/
enum xssfDataType {
BOOL,
ERROR,
FORMULA,
INLINESTR,
SSTINDEX,
NUMBER,
}
/**
* Derived from http://poi.apache.org/spreadsheet/how-to.html#xssf_sax_api
*
* Also see Standard ECMA-376, 1st edition, part 4, pages 1928ff, at
* http://www.ecma-international.org/publications/standards/Ecma-376.htm
*
* A web-friendly version is http://openiso.org/Ecma/376/Part4
*/
class MyXSSFSheetHandler extends DefaultHandler {
/**
* Table with styles
*/
private StylesTable stylesTable;
/**
* Table with unique strings
*/
private ReadOnlySharedStringsTable sharedStringsTable;
/**
* Destination for data
*/
private final PrintStream output;
/**
* Number of columns to read starting with leftmost
*/
private final int minColumnCount;
// Set when V start element is seen
private boolean vIsOpen;
// Set when cell start element is seen;
// used when cell close element is seen.
private xssfDataType nextDataType;
// Used to format numeric cell values.
private short formatIndex;
private String formatString;
private final DataFormatter formatter;
private int thisColumn = -1;
// The last column printed to the output stream
private int lastColumnNumber = -1;
// Gathers characters as they are seen.
private StringBuffer value;
/**
* Accepts objects needed while parsing.
*
* @param styles Table of styles
* @param strings Table of shared strings
* @param cols Minimum number of columns to show
* @param target Sink for output
*/
public MyXSSFSheetHandler(
StylesTable styles,
ReadOnlySharedStringsTable strings,
int cols,
PrintStream target) {
this.stylesTable = styles;
this.sharedStringsTable = strings;
this.minColumnCount = cols;
this.output = target;
this.value = new StringBuffer();
this.nextDataType = xssfDataType.NUMBER;
this.formatter = new DataFormatter();
}
/*
* (non-Javadoc)
* @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
if ("inlineStr".equals(name) || "v".equals(name)) {
vIsOpen = true;
// Clear contents cache
value.setLength(0);
}
// c => cell
else if ("c".equals(name)) {
// Get the cell reference
String r = attributes.getValue("r");
int firstDigit = -1;
for (int c = 0; c < r.length(); ++c) {
if (Character.isDigit(r.charAt(c))) {
firstDigit = c;
break;
}
}
thisColumn = nameToColumn(r.substring(0, firstDigit));
// Set up defaults.
this.nextDataType = xssfDataType.NUMBER;
this.formatIndex = -1;
this.formatString = null;
String cellType = attributes.getValue("t");
String cellStyleStr = attributes.getValue("s");
if ("b".equals(cellType))
nextDataType = xssfDataType.BOOL;
else if ("e".equals(cellType))
nextDataType = xssfDataType.ERROR;
else if ("inlineStr".equals(cellType))
nextDataType = xssfDataType.INLINESTR;
else if ("s".equals(cellType))
nextDataType = xssfDataType.SSTINDEX;
else if ("str".equals(cellType))
nextDataType = xssfDataType.FORMULA;
else if (cellStyleStr != null) {
// It's a number, but almost certainly one
// with a special style or format
int styleIndex = Integer.parseInt(cellStyleStr);
XSSFCellStyle style = stylesTable.getStyleAt(styleIndex);
this.formatIndex = style.getDataFormat();
this.formatString = style.getDataFormatString();
if (this.formatString == null)
this.formatString = BuiltinFormats.getBuiltinFormat(this.formatIndex);
}
}
}
/*
* (non-Javadoc)
* @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
*/
public void endElement(String uri, String localName, String name)
throws SAXException {
String thisStr = null;
// v => contents of a cell
if ("v".equals(name)) {
// Process the value contents as required.
// Do now, as characters() may be called more than once
switch (nextDataType) {
case BOOL:
char first = value.charAt(0);
thisStr = first == '0' ? "FALSE" : "TRUE";
break;
case ERROR:
thisStr = "\"ERROR:" + value.toString() + '"';
break;
case FORMULA:
// A formula could result in a string value,
// so always add double-quote characters.
thisStr = '"' + value.toString() + '"';
break;
case INLINESTR:
// TODO: have seen an example of this, so it's untested.
XSSFRichTextString rtsi = new XSSFRichTextString(value.toString());
thisStr = '"' + rtsi.toString() + '"';
break;
case SSTINDEX:
String sstIndex = value.toString();
try {
int idx = Integer.parseInt(sstIndex);
XSSFRichTextString rtss = new XSSFRichTextString(sharedStringsTable.getEntryAt(idx));
thisStr = '"' + rtss.toString() + '"';
}
catch (NumberFormatException ex) {
output.println("Failed to parse SST index '" + sstIndex + "': " + ex.toString());
}
break;
case NUMBER:
String n = value.toString();
if (this.formatString != null)
thisStr = formatter.formatRawCellContents(Double.parseDouble(n), this.formatIndex, this.formatString);
else
thisStr = n;
break;
default:
thisStr = "(TODO: Unexpected type: " + nextDataType + ")";
break;
}
// Output after we've seen the string contents
// Emit commas for any fields that were missing on this row
if (lastColumnNumber == -1) {
lastColumnNumber = 0;
}
for (int i = lastColumnNumber; i < thisColumn; ++i)
output.print(',');
// Might be the empty string.
output.print(thisStr);
// Update column
if (thisColumn > -1)
lastColumnNumber = thisColumn;
} else if ("row".equals(name)) {
// Print out any missing commas if needed
if (minColumns > 0) {
// Columns are 0 based
if (lastColumnNumber == -1) {
lastColumnNumber = 0;
}
for (int i = lastColumnNumber; i < (this.minColumnCount); i++) {
output.print(',');
}
}
// We're onto a new row
output.println();
lastColumnNumber = -1;
}
}
/**
* Captures characters only if a suitable element is open.
* Originally was just "v"; extended for inlineStr also.
*/
public void characters(char[] ch, int start, int length)
throws SAXException {
if (vIsOpen)
value.append(ch, start, length);
}
/**
* Converts an Excel column name like "C" to a zero-based index.
*
* @param name
* @return Index corresponding to the specified name
*/
private int nameToColumn(String name) {
int column = -1;
for (int i = 0; i < name.length(); ++i) {
int c = name.charAt(i);
column = (column + 1) * 26 + c - 'A';
}
return column;
}
}
///////////////////////////////////////
private OPCPackage xlsxPackage;
private int minColumns;
private PrintStream output;
/**
* Creates a new XLSX -> CSV converter
*
* @param pkg The XLSX package to process
* @param output The PrintStream to output the CSV to
* @param minColumns The minimum number of columns to output, or -1 for no minimum
*/
public ApacheXLSX2CSV(OPCPackage pkg, PrintStream output, int minColumns) {
this.xlsxPackage = pkg;
this.output = output;
this.minColumns = minColumns;
}
/**
* Parses and shows the content of one sheet
* using the specified styles and shared-strings tables.
*
* @param styles
* @param strings
* @param sheetInputStream
*/
public void processSheet(
StylesTable styles,
ReadOnlySharedStringsTable strings,
InputStream sheetInputStream)
throws IOException, ParserConfigurationException, SAXException {
InputSource sheetSource = new InputSource(sheetInputStream);
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
SAXParser saxParser = saxFactory.newSAXParser();
XMLReader sheetParser = saxParser.getXMLReader();
ContentHandler handler = new MyXSSFSheetHandler(styles, strings, this.minColumns, this.output);
sheetParser.setContentHandler(handler);
sheetParser.parse(sheetSource);
}
/**
* Initiates the processing of the XLS workbook file to CSV.
*
* @throws IOException
* @throws OpenXML4JException
* @throws ParserConfigurationException
* @throws SAXException
*/
public void process()
throws IOException, OpenXML4JException, ParserConfigurationException, SAXException {
ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(this.xlsxPackage);
XSSFReader xssfReader = new XSSFReader(this.xlsxPackage);
StylesTable styles = xssfReader.getStylesTable();
XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
int index = 0;
while (iter.hasNext()) {
InputStream stream = iter.next();
String sheetName = iter.getSheetName();
this.output.println();
this.output.println(sheetName + " [index=" + index + "]:");
processSheet(styles, strings, stream);
stream.close();
++index;
}
}
public static void main(String[] args) throws Exception
{
String dataPath = "src/featurescomparison/workingwithworksheets/converttocsv/data/";
File xlsxFile = new File(dataPath + "workbook.xls");
if (!xlsxFile.exists())
{
System.err.println("Not found or not a file: " + xlsxFile.getPath());
return;
}
int minColumns = -1;
if (args.length >= 2)
minColumns = Integer.parseInt(args[1]);
// The package open is instantaneous, as it should be.
OPCPackage p = OPCPackage.open(xlsxFile.getPath(), PackageAccess.READ);
ApacheXLSX2CSV xlsx2csv = new ApacheXLSX2CSV(p, System.out, minColumns);
xlsx2csv.process();
}
//GcExcel 創建worksheet
Workbook wb = new Workbook();
wb.getWorksheets().add();
wb.save("TestOutput/GcExcel/Workbook.xlsx");
//POI 創建worksheet
Workbook wb = new XSSFWorkbook();
Sheet sheet1 = wb.createSheet("sheet1");
Sheet sheet2 = wb.createSheet("sheet2");
try (OutputStream fileOut = new FileOutputStream("TestOutput/Poi/Workbook.xlsx")) {
wb.write(fileOut);
} catch (IOException e) {
throw new RuntimeException(e);
}
//GcExcel 創建日期格式的單元格
Workbook wb = new Workbook();
IWorksheet sheet1 = wb.getWorksheets().get(0);
sheet1.getRange(0, 0).setValue(new Date());
sheet1.getRange(0, 1).setValue(new Date());
sheet1.getRange(0, 1).setNumberFormat("m/d/yy h:mm");
sheet1.getRange(0, 2).setValue(Calendar.getInstance());
sheet1.getRange(0, 2).setNumberFormat("m/d/yy h:mm");
wb.save("TestOutput/GcExcel/CreatingDateCell.xlsx");
//Apache POI 創建日期格式的單元格
Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet1 = wb.createSheet("sheet1");
Row row = sheet1.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue(new Date());
CellStyle style = wb.createCellStyle();
style.setDataFormat(createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(style);
cell = row.createCell(2);
cell.setCellValue(Calendar.getInstance());
cell.setCellStyle(style);
try (OutputStream fileOut = new FileOutputStream("TestOutput/Poi/CreatingDateCell.xlsx")) {
wb.write(fileOut);
} catch (IOException e) {
throw new RuntimeException(e);
}
//例如希望從Excel上獲取特定范圍的數據
//GcExcel
Workbook wb = new Workbook();
IWorksheet sheet1 = wb.getWorksheets().get(0);
Object[][] values = (Object[][]) sheet1.getRange("A1:Z26").getValue();
//Apache POI
Workbook wb = new XSSFWorkbook();
wb.createSheet();
for (Sheet sheet : wb) {
for (Row row : sheet) {
for (Cell cell : row) {
//操作單元格獲取值
}
}
}
更多代碼比較和示例,請參考: GcExcel與POI代碼比較 在線示例
為什么選擇 GcExcel
-
速度快、性能高
GcExcel 的平均速度是 Apache POI 的 7 倍,占用內存僅為 1/7
-
兼容 SpreadJS 前端電子表格
GcExcel 支持 SSJSON 和 SJS,可與 SpreadJS 搭配解決前后端需求
-
剪切、復制、粘貼圖片和形狀
支持對圖片或形狀執行剪切、復制、粘貼等剪貼板操作
-
支持數據切片器
內置切片器樣式,可執行剪切、復制和篩選,支持自定義選項
-
支持 480 多種 Excel 公式
內置種類豐富的計算函數,支持自定義公式
-
支持 64 種圖表類型
除地圖類型外,支持所有 Excel 2016 版本的圖表類型
-
支持應用高級過濾器
包括對數字、文本、顏色、圖標執行過濾
-
導入和導出 CSV
可明顯提高文件的傳輸速度和讀取效率
-
批量打印
可將 Excel 表單導出為 PDF(確保格式不變),實現批量打印
-
與 Excel 一致的條件格式
可使用與 Office 完全相同的文檔對象模型
-
多種排序支持
可按值、多值、字體顏色和圖標排序,支持自定義排序
-
支持迷你圖
GcExcel 支持迷你圖和迷你圖組,可在單元格中可視化數據
三大應用場景
數據處理
實現類 Excel 的數據處理服務
GcExcel 支持 Excel,CSV導入,提供區域操作方式輕松處理 Excel 數據。常用于數據清洗,數據抽取,結構化數據等場景的業務需求。
文件生成
輕松實現服務端定時導出和自動報送
內置PDF,CSV,HTML,圖片等多種文件格式導出,同時與 SpreadJS 保持兼容,支持 SJS 和 SSJSON 格式。常用于計量檢測,Lims等系統中。
可與純前端表格控件 SpreadJS 前后端兼容
GcExcel 天然與 SpreadJS 前后端兼容,可直接導入 SSJSON 格式,在不依賴 Office、POI 和第三方軟件的情況下,滿足在線文檔的前后端數據同步、在線填報與服務端批量導出與打印,以及類 Excel 報表模板設計與服務端高性能處理等功能,為您開發的應用程序提供整套 類 Excel 全棧解決方案。