07版Excle文件解析(超大文件)

由于现存的Excel(07)解析API 只有apache 的poi能够使用,但是如果文件过于庞大,poi解析就有问题了,占用很大的内存

而且速度很慢,我们自己写了一个解析07版Excel的程序,有兴趣的朋友可以看看,很简单,效率还不错

解析的代码见附件 :07Excel_source_code.zip

下面是使用的代码:

1.验证是否是07+版excel(07版以上的excel构造相同)  代码在07Excel_source_code.zip下excel包的 ExcelUtils.java

      /**

* Excel 2007+ using the OOXML format(actually is a zip)

* @return

*/

public static boolean isOOXML(InputStream inputStream) {

try {

return inputStream.read() == 0x50 && inputStream.read() == 0x4b

&& inputStream.read() == 0x03 && inputStream.read() == 0x04;

} catch (IOException e) {

throw new RuntimeException(e);

}

}

2.通过上面的方法进行判断 (03版直接用jxl进行解析) 这里只讲解07+版的解析方式

public List<CommonChatObject> readExcel() {

List<ObjectList > list = new LinkedList<ObjectList >();

SimpleXLSXWorkbook workbook = new SimpleXLSXWorkbook(this.file); //传入你要解析的07Excel文件(假设该文件只有两列 id,name)

Sheet sheet = workbook.getSheet(0);

List<Cell[]> rows = sheet.getRows();

if (rows.size() > 1) {

for (int i = 1; i < rows.size(); i++) {     //从1开始,跳过列名

ObjectList chat = new ObjectList();    定义一个对象(对象字段与excel的列对应)

                            //下面开始解析

Cell[] cell = rows.get(i);

if (StringUtils.isBlank(cell[0].getValue())) {

continue;

}

String id= cell[0].getValue();

String name = cell[1].getValue();

chat.setId(id);

chat.setName(name);

list.add(chat);

}

}

return list;      //得到解析内容

}

————————————————————————————————————————————————————

这里整理了一个jar包,可以直接使用,能够解析07与03版  

//测试类

public static void main(String[] args) {

// check is office2007 or 03 version

ExcelUtils.getExcelExtensionName(new File("/07.xlsx"));

ReaderSupport rxs = ReaderSupport.newInstance(ReaderSupport.TYPE_XLSX, new File("/in.xlsx"));   //如果是07第一个参数ReaderSupport.TYPE_XLSX,03第一个参数是ReaderSupport.TYPE_XLS

rxs.open();

ExcelRowIterator it = rxs.rowIterator();

while (it.nextRow()) {

System.out.println(it.getCellValue(0));

}

rxs.close();

WriterSupport wxs = WriterSupport.newInstance(WriterSupport.TYPE_XLSX, new File("/out.xlsx"));    //同上

wxs.open();

wxs.increaseRow();

for (int i = 0; i < 5; i++) {

wxs.increaseRow();

wxs.writeRow(new String[] { "test" + i });

}

wxs.close();

}

jar 包见附件excel.jar

猜你喜欢

转载自yrandy.iteye.com/blog/1139836