arc*_*rag 5 java excel scripting excel-2007 apache-poi
我的老板习惯在我们的数据库上执行查询,返回数万行并将它们保存到excel文件中.作为实习生,我经常不得不编写与这些文件中的信息一起使用的脚本.到目前为止,我已经尝试过VBScript和Powershell来满足我的脚本需求.即使是最简单的任务,这两个任务都可能需要几分钟才能执行,这意味着脚本完成后将花费大部分时间为8小时.
我现在的解决方法就是编写一个PowerShell脚本,从xlsx文件中删除所有逗号和换行符,将.xlsx文件保存到.csv,然后让Java程序处理数据收集和输出,并让我的脚本在完成后清理.csv文件.对于我目前的项目,这只需要几秒钟就可以运行,但我不禁想知道下一个项目是否有更优雅的选择.有什么建议?
使用.xlsx文件时,我一直遇到各种奇怪的错误.
这是使用Apache POI遍历.xlsx文件的简单示例.另请参阅升级到POI 3.5,包括将现有HSSF Usermodel代码转换为SS Usermodel(适用于XSSF和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;
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 Cell.CELL_TYPE_BLANK:
System.out.print("EMPTY");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
System.out.print(cell.getDateCellValue());
} else {
System.out.print(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
System.out.print(cell.getCellFormula());
break;
default:
System.out.print("DEFAULT");
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11388 次 |
| 最近记录: |