<分区>
我的老板习惯于对我们的数据库执行查询,返回数万行并将它们保存到 excel 文件中。作为实习生,我经常需要编写脚本来处理这些文件中的信息。到目前为止,我已经尝试使用 VBScript 和 Powershell 来满足我的脚本编写需求。即使是最简单的任务,这两项都可能需要几分钟才能完成,这意味着脚本完成后将花费一天 8 小时的大部分时间。
我现在的解决方法是简单地编写一个 PowerShell 脚本,从 xlsx 文件中删除所有逗号和换行符,将 .xlsx 文件保存为 .csv,然后让 Java 程序处理数据收集和输出,并让我的脚本在完成后清理 .csv 文件。对于我当前的项目,这只需要几秒钟的时间,但我不禁想知道我的下一个项目是否有更优雅的替代方案。有什么建议吗?
I kept getting all kinds of weird errors when working with .xlsx files.
这是一个使用 Apache POI 的简单示例遍历 .xlsx
文件,更新到 POI v5。另见 Upgrading to POI 3.5, including converting existing HSSF Usermodel code to SS Usermodel (for XSSF and HSSF) .
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/** @see https://stackoverflow.com/a/3562214/230513 */
public class XlsxReader {
public static void main(String[] args) throws IOException {
InputStream myxls = new FileInputStream("test.xlsx");
Workbook book = new XSSFWorkbook(myxls);
FormulaEvaluator eval =
book.getCreationHelper().createFormulaEvaluator();
Sheet sheet = book.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
printCell(cell, eval);
System.out.print("; ");
}
System.out.println();
}
myxls.close();
}
private static void printCell(Cell cell, FormulaEvaluator eval) {
switch (cell.getCellType()) {
case BLANK:
System.out.print("EMPTY");
break;
case STRING:
System.out.print(cell.getStringCellValue());
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
System.out.print(cell.getDateCellValue());
} else {
System.out.print(cell.getNumericCellValue());
}
break;
case BOOLEAN:
System.out.print(cell.getBooleanCellValue());
break;
case FORMULA:
System.out.print(cell.getCellFormula());
break;
default:
System.out.print("DEFAULT");
}
}
}