使用 POI HSSF 出错 [英] Getting error using POI HSSF

查看:41
本文介绍了使用 POI HSSF 出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用 MS Office 2003 打开 Excel 工作表时出现错误.此 Excel 工作表是使用 HSSFWorkbook 创建的,实现了用户模型范围 org.apache.poi.hssf.usermodel

I'm getting an error when trying to open an Excel sheet with MS office 2003. This Excel sheet is created using HSSFWorkbook, implementing the usermodel scope org.apache.poi.hssf.usermodel

在 Microsoft Excel 2003 中:太多不同的单元格格式".在 Microsoft Excel 2007/2010 中,文件可能会产生以下错误消息:Excel 在文件中发现不可读的内容".这是关于单元格格式,请参考以下页面:

In Microsoft Excel 2003: "Too many different cell formats". In Microsoft Excel 2007/2010, files may produce the following error message: "Excel found unreadable content in the file". This is regarding cell formats, please refer to the below page:

http://support.microsoft.com/kb/213904

那么我该如何在代码中解决这个问题?

So how can I fix this issue in code?

推荐答案

Excel 对您可以拥有的不同单元格样式的数量有限制,而且低得惊人.对于不熟悉 POI 的人来说,一个常见的问题是他们跳过了工作簿范围内的单元格样式,而是为每个单元格创建一个单元格样式.这很快将它们推到了 Excel 中的极限......

Excel has a limit on the number of different cells styles you can have, and it's surprisingly low. A common problem for people new to working with POI is that they skip over the bit about cell styles being workbook wide, and instead they create one cell style per cell. This quickly pushes them over the limit in Excel...

您以前编写代码的地方可能看起来像

Where you code might previously have looked something like

Sheet s = wb.createSheet();
for (int rn=0; rn<=10; rn++) {
    Row r = s.createRow(rn);
    for (int cn=0; cn<=4; cn++) {
        Cell c = r.createCell(c);
        c.setCellValue( getMyCellValue(rn,cn) );

        CellStyle cs = wb.createCellStyle();
        cs.setBold(true);
        if (cn == 2) { 
            cs.setDataFormat( DataFormat.getFormat(yyyy/mm/dd) );
        }
        c.setCellStyle(cs);
    }
}

相反,您需要从一开始就创建单元格样式,例如

You instead need to pull your cell style creation out to the start, something like

CellStyle bold = wb.createCellStyle();
bold.setBold(true);

CellStyle boldDate = wb.createCellStyle();
boldDate.setBold(true);
boldDate.setDataFormat( DataFormat.getFormat(yyyy/mm/dd) );

Sheet s = wb.createSheet();
for (int rn=0; rn<=10; rn++) {
    Row r = s.createRow(rn);
    for (int cn=0; cn<=4; cn++) {
        Cell c = r.createCell(c);
        c.setCellValue( getMyCellValue(rn,cn) );

        CellStyle cs = bold;
        if (cn == 2) { 
            cs = boldDate;
        }
        c.setCellStyle(cs);
    }
}

这篇关于使用 POI HSSF 出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆