Java 导出 Excel 指定列为数字类型
要将 Excel 某列导出为数字类型,可以使用 Java 代码结合 Apache POI 库来实现。下面是一个简单的示例:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
public class ExcelColumnToNumber {
public static void main(String[] args) {
try {
// 读取 Excel 文件
FileInputStream file = new FileInputStream('input.xlsx');
Workbook workbook = WorkbookFactory.create(file);
Sheet sheet = workbook.getSheetAt(0);
// 指定要导出为数字类型的列索引(从 0 开始)
int columnToExport = 1;
// 遍历每一行,将指定列的单元格设置为数字类型
for (Row row : sheet) {
Cell cell = row.getCell(columnToExport);
if (cell != null) {
cell.setCellType(CellType.NUMERIC);
}
}
// 保存修改后的 Excel 文件
FileOutputStream outFile = new FileOutputStream('output.xlsx');
workbook.write(outFile);
outFile.close();
System.out.println('导出成功!');
} catch (Exception e) {
e.printStackTrace();
}
}
}
在上面的示例中,我们首先使用 FileInputStream 类读取 Excel 文件,然后使用 WorkbookFactory 类创建 Workbook 对象来表示整个 Excel 文件。接下来,我们获取第一个工作表并指定要导出为数字类型的列索引。然后,我们遍历每一行,并将指定列的单元格类型设置为数字类型。最后,我们使用 FileOutputStream 类将修改后的 Excel 文件保存到磁盘上。
请注意,上述示例中使用的是 Apache POI 库的版本 3.17。如果你使用的是其他版本的 Apache POI 库,可能需要稍作调整。
原文地址: https://www.cveoy.top/t/topic/qyfo 著作权归作者所有。请勿转载和采集!