首页 技术 正文
技术 2022年11月15日
0 收藏 596 点赞 4,541 浏览 5768 个字

1.目前测试了20M的文件,可以读取。

【Java POI】POI基于事件驱动解析大数据量2007版本Excel,空值导致列错位问题

2.支持单个工作表1万+的数据行数,耗时如图。

【Java POI】POI基于事件驱动解析大数据量2007版本Excel,空值导致列错位问题

3.以下是关键地方处理的代码

 //Accepts objects needed while parsing.
// @param styles Table of styles
// @param strings Table of shared strings
// @param cols Minimum number of columns to show
// @param target Sink for output
public MyXSSFSheetHandler(
StylesTable styles,
ReadOnlySharedStringsTable strings,
int cols,
PrintStream target) {
this.stylesTable = styles;
this.sharedStringsTable = strings;
this.minColumnCount = cols;
this.output = target;
this.value = new StringBuffer();
this.nextDataType = xssfDataType.NUMBER;
this.formatter = new DataFormatter();
rowlist = new ArrayList<String>(0);
rowReader = new RowReader();
rowMap = new HashMap<Integer, String>(0);
rowString = new StringBuffer();
}
// @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException
{ if ("inlineStr".equals(name) || "v".equals(name))
{
vIsOpen = true;
// Clear contents cache
value.setLength(0);
}
// c => cell
else if ("c".equals(name))
{
// Get the cell reference
String r = attributes.getValue("r");
int firstDigit = -1;
for (int c = 0; c < r.length(); ++c)
{
if (Character.isDigit(r.charAt(c)))
{
firstDigit = c;
break;
}
}
thisColumn = nameToColumn(r.substring(0, firstDigit)); // Set up defaults.
this.nextDataType = xssfDataType.NUMBER;
this.formatIndex = -1;
this.formatString = null;
String cellType = attributes.getValue("t");
String cellStyleStr = attributes.getValue("s");
if ("b".equals(cellType))
nextDataType = xssfDataType.BOOL;
else if ("e".equals(cellType))
nextDataType = xssfDataType.ERROR;
else if ("inlineStr".equals(cellType))
nextDataType = xssfDataType.INLINESTR;
else if ("s".equals(cellType))
nextDataType = xssfDataType.SSTINDEX;
else if ("str".equals(cellType))
nextDataType = xssfDataType.FORMULA;
else if (cellStyleStr != null) {
// It's a number, but almost certainly one
// with a special style or format
int styleIndex = Integer.parseInt(cellStyleStr);
XSSFCellStyle style = stylesTable.getStyleAt(styleIndex);
this.formatIndex = style.getDataFormat();
this.formatString = style.getDataFormatString();
if (this.formatString == null)
this.formatString = BuiltinFormats.getBuiltinFormat(this.formatIndex);
}
} } // @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
public void endElement(String uri, String localName, String name)
throws SAXException
{ String thisStr = null; // v => contents of a cell
if ("v".equals(name))
{
// Process the value contents as required.
// Do now, as characters() may be called more than once
switch (nextDataType) { case BOOL:
char first = value.charAt(0);
thisStr = first == '0' ? "FALSE" : "TRUE";
break; case ERROR:
thisStr = "\"ERROR:" + value.toString() + '"';
break; case FORMULA:
// A formula could result in a string value,
// so always add double-quote characters.
thisStr = '"' + value.toString() + '"';
break; case INLINESTR:
// TODO: have seen an example of this, so it's untested.
XSSFRichTextString rtsi = new XSSFRichTextString(value.toString());
thisStr = '"' + rtsi.toString() + '"';
break; case SSTINDEX:
String sstIndex = value.toString();
try {
int idx = Integer.parseInt(sstIndex);
XSSFRichTextString rtss = new XSSFRichTextString(sharedStringsTable.getEntryAt(idx));
thisStr = '"' + rtss.toString() + '"';
} catch (NumberFormatException ex) {
output.println("Failed to parse SST index '" + sstIndex + "': " + ex.toString());
}
break; case NUMBER:
String n = value.toString();
if (this.formatString != null)
thisStr = formatter.formatRawCellContents(Double.parseDouble(n), this.formatIndex, this.formatString);
else
thisStr = n;
break; default:
thisStr = "(TODO: Unexpected type: " + nextDataType + ")";
break;
} // Output after we've seen the string contents
// Emit commas for any fields that were missing on this row
if (lastColumnNumber == -1)
{
lastColumnNumber = 0;
}
for (int i = lastColumnNumber; i < thisColumn; ++i)
{
rowString.append(',');//每天加一个单元格的值到字符串中就追加一个逗号(末尾不添加)
//output.print(','); 可以看到使用output是可以将每一个单元格使用逗号分割
              //但是如果使用rowlist添加到列表中,却始终无法得到空单元格的内容
              //也就是说:空单元格被忽略了。
              //具体请参照标红的地方进行处理:使用字符串拼接的方式获得完整的行数据,再使用逗号拆分组合成rowMap
}
rowString.append(thisStr);// 这条code放在for后面,如果放在前面,会导致0和1两个单元格合为一个单元格。
// Might be the empty string.
//output.print(thisStr);
rowlist.add(thisStr);
// Update column
if (thisColumn > -1)
{
lastColumnNumber = thisColumn;
}
rowIndex++;
}
else if ("row".equals(name))
{ // Print out any missing commas if needed
if (minColumns > 0)
{
// Columns are 0 based
if (lastColumnNumber == -1)
{
lastColumnNumber = 0;
}
for (int i = lastColumnNumber; i < (this.minColumnCount); i++)
{
output.print(',');
}
} // We're onto a new row output.println();
output.println(countrows++);
lastColumnNumber = -1;
rowIndex = 0;
//rowMap = rowReader.getRowMap(rowlist);
rowMap = rowReader.getRowMapByString(rowString.toString());
// ADD =
rowLst1000.add(rowMap);
rowMap = null;
rowMap = new HashMap<Integer, String>(0);
if (countrows % 1000 == 0)
{
rowLst1000n.add(rowLst1000);
rowLst1000 = null;
rowLst1000 = new ArrayList<Map<Integer, String>>(0);
}
rowlist.clear();
System.out.println(rowString.toString());
rowString = null;
rowString = new StringBuffer();
}
}

以上是我自己的处理方式,当然还有其他的处理方式,再研究吧。毕竟写到此处的时候,我不过是一个不到1年经验的小菜鸟。

\

补充:

  上面的处理方式不够明智,如果单元格中的文本本生就带有逗号,那么会导致分割错误。

  建议:

143          if (lastColumnNumber == -1)
144 {
145 lastColumnNumber = 0;
              // 此处使用list或者map进行存储
              list.add(null);//添加一个空值
146 }
147 for (int i = lastColumnNumber; i < thisColumn; ++i)
            此处改为:
            for (int i = lastColumnNumber + 1; i < thisColumn; ++i) // lastColumnNumber + 1 确保不会因为连续两个空单元格而出错。
148           { 
149             //rowString.append(',');//每天加一个单元格的值到字符串中就追加一个逗号(末尾不添加) 150 //output.print(','); 可以看到使用output是可以将每一个单元格使用逗号分割
              //但是如果使用rowlist添加到列表中,却始终无法得到空单元格的内容
              //也就是说:空单元格被忽略了。
              //具体请参照标红的地方进行处理:使用字符串拼接的方式获得完整的行数据,再使用逗号拆分组合成rowMap
              
              // 此处使用list或者map进行存储
              list.add(null);//添加一个空值
151                 }
            // if 和 for 之后再添加当前单元格字符串
            list.add(thisStr);记住:可以打断点自己跑一跑,不难发现,for循环中所追加的逗号是当前单元格添加的,所以并不是说第一个格之后和第二个单元格之前刻意添加的。明白这个if和for的具体作用后,就能顺利的为空单元格赋值,且绕开使用字符串拼接导致的潜在问题。

下面附上其余代码的参照地址:

java使用POI通过事件模型解析超过40M的Excel文件,解决空单元格问题

http://www.360sdn.com/java/2014/0524/3392.html

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,494
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295