POI 操作 wrod 和 excel 文档

java 利用POI 读写 word excel ,还算方便

1. 遇到 java.io.IOException: Unable to read entire header; 0 bytes read; expected 512 bytes

主要是打开多个文档读写,就会出问题。 打开文档需要用单例模式
在一个线程里开了一个 HSSFWorkbok(excel workbook obj),在另外一个函数中又开了一个,就会出现这个问题

还有一个大坑就是: 如果打开两个excel 文件, 虽然这是两个file, 但是依然会出现这个问题
我的测试函数是这样:
    /**
     * This function confirms , CANNOT open two HSSFWorkbook in same time, even opent two different file
     * @param filepath1
     * @param filepath2
     */
    public void openTwoXlsSametime(String filepath1,String filepath2){
	try {
	    FileInputStream fin1=new FileInputStream(new File(filepath1));
	    FileInputStream fin2=new FileInputStream(new File(filepath2));
	    HSSFWorkbook wk1 = new HSSFWorkbook(fin1);
	    HSSFWorkbook wk2 = new HSSFWorkbook(fin2);
	    wk1.getSheet("Workflow");
	    wk2.getSheet("Workflow");
	} catch (FileNotFoundException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	} catch (IOException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	
    }


你会看到异常抛出,其实什么都没做,就是打开两个excel

2. 另外, 我还得到一个经验

就是 new FileOutputStream(new File()),这个文件如果存在,就会被清为0, 难道我应该以append 方式打开  new FileOutputStream(new File(),true) ? 确实这样,如果要即读又写,必须FileOutputStream 作为append 模式

我遇到的问题是,一个excel 既读又写,读出一个sheet 表内容,作处理后写入另一个sheet 中,这个也不行,不知道如何做
于是我只好处理excel 后, 写入csv 文本文件,然后手工拷贝到sheet 表中

3. POI write XSSFWorkbook, 写excel 日期字符串,用setCellValue(stringvalue), 打开excel 总是发现有个 leading aspotrophe ' 在里面,折腾好久,后来终于找到解决方案,
XSSFworkbook 写字符串类型数据,应该用下面方法:
XSSFCellStyle textFormatStyle = (XSSFCellStyle) workbook.createCellStyle();
               textFormatStyle.setDataFormat((short)BuiltinFormats.getBuiltinFormat("text"));
XSSFCell cell = (XSSFCell) r.createCell(colIndix);
cell.setCellStyle(textFormatStyle);

参考: http://apache-poi.1045710.n5.nabble.com/Adding-dates-as-text-with-a-leading-apostrophe-td3283872.html

4. POI读写 excel ,从一个excel 中 读, 然后再写入另一个excel 中,
如何把读excel 中相应cell style ,正确的写入 excel 中?
写excel 的 cellStyle 不能简单的 new Style, 会报错。错误exception 记不得了,网上可以查到
必须读取,克隆,然后使用
origStyle = titleRow.getCell(ri).getCellStyle();
textFormatStyle = (XSSFCellStyle) wWorkbook.createCellStyle();
textFormatStyle.cloneStyleFrom(origStyle);
XSSFCell nCell = (XSSFCell) row0.createCell(ri);
nCell.setCellStyle(textFormatStyle);

5. 之前部署在Jekins 上运行,总是报错
org.apache.poi.POIXMLException: java.lang.reflect.InvocationTargetException
有网页说, 是sellCellValue(value) 写入了一个空值,引起的, 检查了空值还是有;
有网页说, 是包冲突引起的, 有一种原因是引用了旧的poi, 另外还有一个是说xmlbean 冲突。
而我 把 xmlbean 2.3 替换为 2.6 之后,该错误消失了

6. 之前运行了很多次都没有问题,也没有改代码,忽然一天运行,就出现下面Exception:
java.lang.IllegalStateException: The maximum number of Cell Styles was exceeded. You can define up to 64000 style in a .xlsx Workbook
参考: https://github.com/MetadataConsulting/spreadsheet-builder/issues/8
检查代码,发现我在循环中重复 myStyle= (XSSFCellStyle) wWorkbook.createCellStyle();
把 mystyle 定义挪到for 之外, 只是重复赋值。依然不对
干脆只赋值一次,重复使用。

猜你喜欢

转载自david-95-live-cn.iteye.com/blog/2320078