[]
        
立即试用
(Showing Draft Content)

导入和导出.xlsx文档

本节概述了GcExcel Java 如何处理电子表格文档( .xlsx 文件)。

当你使用 GcExcel Java 创建一个工作簿并保存时,会自动将其导出到外部位置或文件夹。当将 Excel 文件导入GcExcel Java(导入文件或打开文件)时,你既可以加载导入的电子表格的整个模型,也可以仅导入数据。GcExcel Java 提供了open 方法,通过 XlsxOpenOptions 类的 setImportFlags 方法可访问的各种导入标志来打开文件。同样,要将工作簿导出为 .xlsx 文件,可以使用 save 方法,并使用 GcExcel 提供的各种保存选项来指定跳过哪些内容以及导出哪些内容。这些选项如下所示:


类名

选项名称

描述

导入选项

XlsxOpenOptions

DoNotAutoFitAfterOpened

指定打开 Excel 文件时是否自动调整行高。

DoNotRecalculateAfterOpened

指定 Excel 文件打开后是否重新计算公式值。

ImportFlags

提供各种标志以导入工作表的各个方面。

DigitalSignatureOnly

指示是否以仅数字签名模式打开工作簿。在仅数字签名模式下,现有签名将被保留,除非你调用 ISignature.Delete。但在此模式下,你只能对现有签名行进行签名、添加不可见签名、删除已签名签名行的数字签名或删除不可见签名。其他更改将被丢弃。修改数字签名后,你需要保存工作簿以提交更改。若要以仅数字签名模式打开工作簿,设为 true。否则,使用正常模式。默认值为 false。

FileFormat

表示打开工作簿时的格式。

Password

xlsx 文件的密码。

导出选项

XlsxSaveOptions

IgnoreFormulas

将 GcExcel 工作表的公式单元格作为值单元格导出到 Excel 中。

ExcludeUnusedStyles

导出文件时排除未使用的样式。

ExcludeUnusedNames

导出文件时排除未使用的名称。

ExcludeEmptyRegionCells

排除空单元格,即位于已使用范围之外且具有样式但不包含数据的单元格。

FileFormat

表示保存工作簿时的格式。

IsCompactMode

指示是否以紧凑模式保存工作簿。默认值为 false。

Password

xlsx 文件的密码。

IncludeAutoMergedCells

指示是否包含自动合并的单元格。默认值为 false。

IncludeBindingSource

指示保存文件时是否包含绑定源。默认值为 true。

要从文件名导入和导出 .xlsx 文档,请参考以下示例代码:

// 创建一个新工作簿。
Workbook workbook = new Workbook();

// 打开xlsx文件。
workbook.open("Basic sales report1.xlsx", OpenFileFormat.Xlsx);

// 将工作簿保存为xlsx文件。
workbook.save("Exported.xlsx", SaveFileFormat.Xlsx);

要从文件流导入和导出 .xlsx 文档,请参考以下示例代码:

  // 创建一个新工作簿。
  var streamworkbook = new Workbook();
  // 创建一个新文件流以打开文件。
InputStream openFile;
try {
    openFile = new FileInputStream("Basic sales report1.xlsx");
    // 打开xlsx文件。
    streamworkbook.open(openFile, OpenFileFormat.Xlsx);
} catch (FileNotFoundException e1) {
    // 自动生成的catch块
    e1.printStackTrace();
}

// 创建一个新文件流以保存文件。
 OutputStream out;
try {
    out = new FileOutputStream("Exported-Stream.xlsx");
     // 将工作簿保存为xlsx文件。
      streamworkbook.save(out, SaveFileFormat.Xlsx);
} catch (FileNotFoundException e) {
    // 自动生成的catch块
    e.printStackTrace();
}

作为另一种常见场景,你可能只需要从电子表格或单元格区域导入数据。为处理此类场景,GcExcel Java 提供了 importData 方法,以便从外部工作表或单元格区域高效加载数据。有关仅导入数据的更多信息,请参阅下面的“仅导入数据”部分。

只导入数据

为了仅从指定的工作表或单元格范围导入数据,GcExcel Java 提供了 importData 方法,该方法打开工作表并为您获取数据。 这种方法在只需要数据并且不需要处理对象模型的其余部分的场景中很有用。 importData 方法使用文件或文件流和工作表的名称作为主要参数,可以指定工作表(sheet)、表格(table)或区域(range)的名称作为数据源。为了获取文件或文件流中使用的工作表和表格的名称,Workbook 类提供了 getNames 方法,该方法返回一个名称的数组。

// Create a new workbook
Workbook workbook = new Workbook();
// Open an excel file.
InputStream fileStream = getResourceStream("AgingReport.xlsx");
// Get the possible import names in the file.
// The names[0] and names[1] are sheet names: "Aging Report", "Invoices".
// The names[2] and names[3] are table names: "'Aging Report'!tblAging", "Invoices!tblInvoices".
String[] names = Workbook.getNames(fileStream);
// The InputStream of the Java platform cannot be read repeatedly, so you need to create another one.
InputStream fileStream2 = getResourceStream("AgingReport.xlsx");
// Import the data of a table "'Aging Report'!tblAging" from the fileStream.
Object[][] data = Workbook.importData(fileStream2, names[2]);
// Assign the data to current workbook.
workbook.getWorksheets().get(0).getRange(0, 0, data.length, data[0].length).setValue(data);

// Save to an excel file
workbook.save("ImportDataForTable.xlsx");

在处理包含多个工作表或许多公式的繁重文件时,可以使用 importData 方法优化加载性能,因为它只读取数据。该方法还提供了重载,您可以在其中指定目标单元格的范围,并且只能读取该特定部分,即使您的文件包含大量数据。

局限性

  • 使用 importData 方法时不考虑公式,因为 CalcEngine 在这种情况下不起作用。 因此,单元格值设置为空。 如果公式在文件中存储了缓存值,GcExcel 将返回该值。

  • 如果工作表名称包含字符 !,例如 “Sheet!1”,无法通过调用 importData(worksheetName) 来解析工作表名称,此函数返回 null。

控制绑定数据导出

当使用 XlsxSaveOptions setIncludeBindingSource 方法将数据导出为 .xlsx 文件时,GcExcel 允许您控制是否将绑定的数据源导出到文件中。

参考以下示例代码,在导出为 .xlsx 文件时排除绑定源:

// 创建一个新工作簿。
var workbook = new Workbook();

// 定义一个JSON数据源。
String dataSource = "{ \"ds\":" +
        "[\n" +
        "   {\"Area\": \"北美洲\",\"City\": \"芝加哥\",\"Category\": \"消费电子产品\",\"Name\": \"Bose 785593 - 0050\",\"Revenue\": 92800},\n" +
        "   {\"Area\": \"北美洲\",\"City\": \"纽约\",\"Category\": \"消费电子产品\",\"Name\": \"Bose 785593 - 0050\",\"Revenue\": 92800},\n" +
        "   {\"Area\": \"南美洲\",\"City\": \"圣地亚哥\",\"Category\": \"消费电子产品\",\"Name\": \"Bose 785593 - 0050\",\"Revenue\": 19550},\n" +
        "   {\"Area\": \"欧洲\",\"City\": \"柏林\",\"Category\": \"消费电子产品\",\"Name\": \"索尼WH - 1000XM4\",\"Revenue\": 30000},\n" +
        "   {\"Area\": \"亚洲\",\"City\": \"东京\",\"Category\": \"消费电子产品\",\"Name\": \"索尼WH - 1000XM4\",\"Revenue\": 45000},\n" +
        "   {\"Area\": \"北美洲\",\"City\": \"洛杉矶\",\"Category\": \"消费电子产品\",\"Name\": \"苹果AirPods\",\"Revenue\": 60000},\n" +
        "   {\"Area\": \"欧洲\",\"City\": \"巴黎\",\"Category\": \"消费电子产品\",\"Name\": \"苹果AirPods\",\"Revenue\": 55000},\n" +
        "   {\"Area\": \"亚洲\",\"City\": \"首尔\",\"Category\": \"消费电子产品\",\"Name\": \"三星Galaxy Buds\",\"Revenue\": 40000},\n" +
        "   {\"Area\": \"南美洲\",\"City\": \"布宜诺斯艾利斯\",\"Category\": \"消费电子产品\",\"Name\": \"三星Galaxy Buds\",\"Revenue\": 35000},\n" +
        "   {\"Area\": \"北美洲\",\"City\": \"多伦多\",\"Category\": \"消费电子产品\",\"Name\": \"Bose 785593 - 0050\",\"Revenue\": 50000}\n" +
        " ]" +
        "}";

// 将数据源添加到工作表。
IWorksheet dataSourceSheet = workbook.getWorksheets().add();
dataSourceSheet.setName("DataSource");
ITable table = dataSourceSheet.getTables().add(dataSourceSheet.getRange("A1:E4"), true);

// 设置绑定路径。
table.setBindingPath("ds");
table.getColumns().get(0).setDataField("Area");
table.getColumns().get(1).setDataField("City");
table.getColumns().get(2).setDataField("Category");
table.getColumns().get(3).setDataField("Name");
table.getColumns().get(4).setDataField("Revenue");

// 设置数据源。
dataSourceSheet.setDataSource(new JsonDataSource(dataSource));

// 创建数据透视表工作表。
IWorksheet pivotSheet = workbook.getWorksheets().get(0);
pivotSheet.setName("PivotSheet");

// 创建数据透视表。
IPivotCache pivotcache = workbook.getPivotCaches().create(table);
IPivotTable pivottable = pivotSheet.getPivotTables().add(pivotcache, pivotSheet.getRange("A1"), "pivottable1");

// 配置数据透视表字段。
IPivotField fieldArea = pivottable.getPivotFields().get("Area");
fieldArea.setOrientation(PivotFieldOrientation.RowField);
IPivotField fieldCity = pivottable.getPivotFields().get("City");
fieldCity.setOrientation(PivotFieldOrientation.RowField);
IPivotField fieldName = pivottable.getPivotFields().get("Name");
fieldName.setOrientation(PivotFieldOrientation.ColumnField);
IPivotField fieldRevenue = pivottable.getPivotFields().get("Revenue");
fieldRevenue.setOrientation(PivotFieldOrientation.DataField);
pivotSheet.getUsedRange().autoFit();
pivottable.setColumnGrand(false);
pivottable.setRowGrand(false);
pivottable.refresh();

XlsxSaveOptions saveOptions = new XlsxSaveOptions();

// 将IncludeBindingSource属性设置为false,以排除绑定源不被导出。
saveOptions.setIncludeBindingSource(false);

// 保存工作簿。
workbook.save("IncludeBindingSourceOption.xlsx", saveOptions);

type=warning

注意:在数据绑定更改表格大小后,setIncludeBindingSource 方法不会将表格恢复到原始大小。此方法仅控制数据是否被导出。