POI导入大excel文件

1package me.shanzhi.test; 2 3import java.io.InputStream; 4import java.util.ArrayList; 5import java.util.Iterator; 6import java.util.List; 7 8import org.apache.poi.openxml4j.opc.OPCPackage; 9import org.apache.poi.xssf.eventusermodel.XSSFReader; 10import org.apache.poi.xssf.model.SharedStringsTable; 11import org.apache.poi.xssf.usermodel.XSSFRichTextString; 12import org.springframework.context.annotation.Scope; 13import org.springframework.stereotype.Component; 14import org.xml.sax.Attributes; 15import org.xml.sax.ContentHandler; 16import org.xml.sax.InputSource; 17import org.xml.sax.SAXException; 18import org.xml.sax.XMLReader; 19import org.xml.sax.helpers.DefaultHandler; 20import org.xml.sax.helpers.XMLReaderFactory; 21 22 23/** 24 * copy from apache.org 25 * depends on poi*.jar, dom4j.jar, stax-api.jar,xmlbeans.jar, xerecesImpl.jar 26 */ 27@Scope("prototype") 28@Component("excel07EventUserModel") 29public class ExampleEventUserModel { 30 31 public void processOneSheet(String filename) throws Exception { 32 OPCPackage pkg = OPCPackage.open(filename); 33 XSSFReader r = new XSSFReader( pkg ); 34 SharedStringsTable sst = r.getSharedStringsTable(); 35 36 XMLReader parser = fetchSheetParser(sst); 37 38 // rId2 found by processing the Workbook 39 // Seems to either be rId# or rSheet# 40 InputStream sheet2 = r.getSheet("rId1"); 41 InputSource sheetSource = new InputSource(sheet2); 42 parser.parse(sheetSource); 43 List<List<String>> sheetContent = ((SheetHandler) parser.getContentHandler()).retVal(); 44 System.err.println(sheetContent.size()); 45 for(List<String> list : sheetContent) { 46 System.out.println(list.get(7)); 47 } 48 sheet2.close(); 49 } 50 51 public void processAllSheets(String filename) throws Exception { 52 OPCPackage pkg = OPCPackage.open(filename); 53 XSSFReader r = new XSSFReader( pkg ); 54 SharedStringsTable sst = r.getSharedStringsTable(); 55 56 XMLReader parser = fetchSheetParser(sst); 57 58 Iterator<InputStream> sheets = r.getSheetsData(); 59 while(sheets.hasNext()) { 60 System.out.println("Processing new sheet:\n"); 61 InputStream sheet = sheets.next(); 62 InputSource sheetSource = new InputSource(sheet); 63 parser.parse(sheetSource); 64 sheet.close(); 65 System.out.println(""); 66 } 67 } 68 69 public XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException { 70 XMLReader parser = 71 XMLReaderFactory.createXMLReader( 72 "org.apache.xerces.parsers.SAXParser" 73 ); 74 ContentHandler handler = new SheetHandler(sst); 75 parser.setContentHandler(handler); 76 return parser; 77 } 78 79 /**  80  * See org.xml.sax.helpers.DefaultHandler javadocs  81  */ 82 private static class SheetHandler extends DefaultHandler { 83 private SharedStringsTable sst; 84 private String lastContents; 85 private boolean nextIsString; 86 87 private List<String> row; 88 89 private List<List<String>> sheet = new ArrayList<List<String>>(); 90 91 //当前列 92 private int curCol = 0; 93 //上一列 94 private int preCol = 0; 95 96 private SheetHandler(SharedStringsTable sst) { 97 this.sst = sst; 98 } 99 100 public List<List<String>> retVal() { 101 return sheet; 102 } 103 104 public void startElement(String uri, String localName, String name, 105 Attributes attributes) throws SAXException { 106 // c => cell 107 if(name.equals("sheetData")) sheet = new ArrayList<List<String>>(); 108 if(name.equals("row")) row = new ArrayList<String>(); 109 if(name.equals("c")) { 110 // Print the cell reference 111 //System.out.print(attributes.getValue("r") + " - "); 112 // Figure out if the value is an index in the SST 113 String cellType = attributes.getValue("t"); 114 String rowStr = attributes.getValue("r"); 115 curCol = getRowIndex(rowStr); 116 117 if(cellType != null && cellType.equals("s")) { 118 nextIsString = true; 119 } else { 120 nextIsString = false; 121 } 122 } 123 // Clear contents cache 124 lastContents = ""; 125 } 126 127 public void endElement(String uri, String localName, String name) 128 throws SAXException { 129 // Process the last contents as required. 130 // Do now, as characters() may be called more than once 131 if(nextIsString) { 132 int idx = Integer.parseInt(lastContents); 133 lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString(); 134 nextIsString = false; 135 } 136 137 // v => contents of a cell 138 // Output after we've seen the string contents 139 if(name.equals("v")) { 140 //System.out.println(lastContents); 141 142 int cols = curCol-preCol;   143             if (cols>1){   144                 for (int i = 0;i < cols-1;i++){   145                     row.add(preCol,"");   146                 }   147             }   148 row.add(curCol - 1 ,lastContents); 149 preCol = curCol;   150 } 151 if(name.equals("row")){ 152 sheet.add(row); 153 curCol = 0;   154                preCol = 0;   155 } 156 } 157 158 public void characters(char[] ch, int start, int length) 159 throws SAXException { 160 lastContents += new String(ch, start, length); 161 } 162 163 //得到列索引,每一列c元素的r属性构成为字母加数字的形式,字母组合为列索引,数字组合为行索引,   164     //如AB45,表示为第(A-A+1)*26+(B-A+1)*26列,45行   165     public int getRowIndex(String rowStr){   166         rowStr = rowStr.replaceAll("[^A-Z]", "");   167         byte[] rowAbc = rowStr.getBytes();   168         int len = rowAbc.length;   169         float num = 0;   170         for (int i=0;i<len;i++){   171             num += (rowAbc[i]-'A'+1)*Math.pow(26,len-i-1 );   172         }   173         return (int) num;   174     }   175 } 176 177 public static void main(String[] args) throws Exception { 178 ExampleEventUserModel example = new ExampleEventUserModel(); 179 example.processOneSheet("D:\\Users\\1月.xlsx"); 180 } 181}
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )

POI导入大excel文件 - HelloWorld