---
title: "POI读写大数据Excel"
author: "lvjun106"
date: "2015-04-10T22:38:09Z"
tags: []
categories: ["开源软件"]
slug: "poi-excel"
draft: false
lastmod: "2015-04-10T22:38:09Z"
id: 2201205
url: "https://lvjun106.iteye.com/blog/2201205"
---

转\[[http://blog.csdn.net/goodkuang2012/article/details/7350985#](http://blog.csdn.net/goodkuang2012/article/details/7350985)]]

 

目前处理Excel的开源javaAPI主要有两种，一是Jxl（Java Excel API）,Jxl只支持Excel2003以下的版本。另外一种是Apache的Jakarta POI,相比于Jxl,POI对微软办公文档的支持更加强大，但是它使用复杂，上手慢。POI可支持更高的Excel版本2007。对Excel的读取，POI有两种模式，一是用户模式，这种方式同Jxl的使用很类似，使用简单，都是将文件一次性读到内存，文件小的时候，没有什么问题，当文件大的时候，就会出现OutOfMemory的内存溢出问题。第二种是事件驱动模式，拿Excel2007来说，其内容采用XML的格式来存储，所以处理excel就是解析XML，而目前使用事件驱动模式解析XML的API是SAX(Simple API for XML)，这种模型在读取XML文档时，并没有将整个文档读入内存，而是按顺序将整个文档解析完，在解析过程中，会主动产生事件交给程序中相应的处理函数来处理当前内容。因此这种方式对系统资源要求不高，可以处理海量数据。笔者曾经做过测试，这种方法处理一千万条，每条五列的数据花费大约11分钟。可见处理海量数据的文件事件驱动是一个很好的方式。而本文中用到的AbstractExcel2003Reader、AbstractExcel2007Reader对Excel的读取都是采用这种POI的事件驱动模式。至于Excel的写操作，对较高版本的Excel2007，POI提供了很好的支持，主要流程是第一步构建工作薄和电子表格对象，第二步在一个流中构建文本文件，第三步使用流中产生的数据替换模板中的电子表格。这种方式也可以处理海量数据文件。AbstractExcel2007Writer就是使用这种方式进行写操作。对于写入较低版本的Excel2003，POI使用了用户模式来处理，就是将整个文档加载进内存，如果数据量大的话就会出现内存溢出的问题，Excel2003Writer就是使用这种方式。据笔者的测试，如果数据量大于3万条，每条8列的话，就会报OutOfMemory的错误。Excel2003中每个电子表格的记录数必须在65536以下，否则就会发生异常。目前还没有好的解决方案，建议对于海量数据写入操作，尽量使用Excel2007。

**\[java]** [view plain](http://blog.csdn.net/goodkuang2012/article/details/7350985 "view plain")[copy](http://blog.csdn.net/goodkuang2012/article/details/7350985 "copy")

 

001. /\**
002. * 抽象Excel2003读取器，通过实现HSSFListener监听器，采用事件驱动模式解析excel2003
003. * 中的内容，遇到特定事件才会触发，大大减少了内存的使用。
004. \*
005. \*/
006. public  class Excel2003Reader implements HSSFListener{
007. private int minColumns = -1;
008. private POIFSFileSystem fs;
009. private int lastRowNumber;
010. private int lastColumnNumber;
011. /\** Should we output the formula, or the value it has? \*/
012. private boolean outputFormulaValues = true;
013. /\** For parsing Formulas \*/
014. private SheetRecordCollectingListener workbookBuildingListener;
015. //excel2003工作薄
016. private HSSFWorkbook stubWorkbook;
017. // Records we pick up as we process
018. private SSTRecord sstRecord;
019. private FormatTrackingHSSFListener formatListener;
020. //表索引
021. private int sheetIndex = -1;
022. private BoundSheetRecord\[] orderedBSRs;
023. @SuppressWarnings("unchecked")
024. private ArrayList boundSheetRecords = new ArrayList();
025. // For handling formulas with string results
026. private int nextRow;
027. private int nextColumn;
028. private boolean outputNextStringRecord;
029. //当前行
030. private int curRow = 0;
031. //存储行记录的容器
032. private List&lt;String&gt; rowlist = new ArrayList&lt;String&gt;();;
033. @SuppressWarnings( "unused")
034. private String sheetName;
035. private IRowReader rowReader;
036. public void setRowReader(IRowReader rowReader){
037. this.rowReader = rowReader;
038. }
039. /\**
040. * 遍历excel下所有的sheet
041. * @throws IOException
042. \*/
043. public void process(String fileName) throws IOException {
044. this.fs = new POIFSFileSystem(new FileInputStream(fileName));
045. MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(
046. this);
047. formatListener = new FormatTrackingHSSFListener(listener);
048. HSSFEventFactory factory = new HSSFEventFactory();
049. HSSFRequest request = new HSSFRequest();
050. if (outputFormulaValues) {
051. request.addListenerForAllRecords(formatListener);
052. } else {
053. workbookBuildingListener = new SheetRecordCollectingListener(
054. formatListener);
055. request.addListenerForAllRecords(workbookBuildingListener);
056. }
057. factory.processWorkbookEvents(request, fs);
058. }
059. /\**
060. * HSSFListener 监听方法，处理 Record
061. \*/
062. @SuppressWarnings("unchecked")
063. public void processRecord(Record record) {
064. int thisRow = -1;
065. int thisColumn = -1;
066. String thisStr = null;
067. String value = null;
068. switch (record.getSid()) {
069. case BoundSheetRecord.sid:
070. boundSheetRecords.add(record);
071. break;
072. case BOFRecord.sid:
073. BOFRecord br = (BOFRecord) record;
074. if (br.getType() == BOFRecord.TYPE\_WORKSHEET) {
075. // 如果有需要，则建立子工作薄
076. if (workbookBuildingListener != null && stubWorkbook == null) {
077. stubWorkbook = workbookBuildingListener
078. .getStubHSSFWorkbook();
079. }
080. sheetIndex++;
081. if (orderedBSRs == null) {
082. orderedBSRs = BoundSheetRecord
083. .orderByBofPosition(boundSheetRecords);
084. }
085. sheetName = orderedBSRs\[sheetIndex].getSheetname();
086. }
087. break;
088. case SSTRecord.sid:
089. sstRecord = (SSTRecord) record;
090. break;
091. case BlankRecord.sid:
092. BlankRecord brec = (BlankRecord) record;
093. thisRow = brec.getRow();
094. thisColumn = brec.getColumn();
095. thisStr = "";
096. rowlist.add(thisColumn, thisStr);
097. break;
098. case BoolErrRecord.sid: //单元格为布尔类型
099. BoolErrRecord berec = (BoolErrRecord) record;
100. thisRow = berec.getRow();
101. thisColumn = berec.getColumn();
102. thisStr = berec.getBooleanValue()+"";
103. rowlist.add(thisColumn, thisStr);
104. break;
105. case FormulaRecord.sid: //单元格为公式类型
106. FormulaRecord frec = (FormulaRecord) record;
107. thisRow = frec.getRow();
108. thisColumn = frec.getColumn();
109. if (outputFormulaValues) {
110. if (Double.isNaN(frec.getValue())) {
111. // Formula result is a string
112. // This is stored in the next record
113. outputNextStringRecord = true;
114. nextRow = frec.getRow();
115. nextColumn = frec.getColumn();
116. } else {
117. thisStr = formatListener.formatNumberDateCell(frec);
118. }
119. } else {
120. thisStr = '"' + HSSFFormulaParser.toFormulaString(stubWorkbook,
121. frec.getParsedExpression()) + '"';
122. }
123. rowlist.add(thisColumn,thisStr);
124. break;
125. case StringRecord.sid://单元格中公式的字符串
126. if (outputNextStringRecord) {
127. // String for formula
128. StringRecord srec = (StringRecord) record;
129. thisStr = srec.getString();
130. thisRow = nextRow;
131. thisColumn = nextColumn;
132. outputNextStringRecord = false;
133. }
134. break;
135. case LabelRecord.sid:
136. LabelRecord lrec = (LabelRecord) record;
137. curRow = thisRow = lrec.getRow();
138. thisColumn = lrec.getColumn();
139. value = lrec.getValue().trim();
140. value = value.equals("")?" ":value;
141. this.rowlist.add(thisColumn, value);
142. break;
143. case LabelSSTRecord.sid:  //单元格为字符串类型
144. LabelSSTRecord lsrec = (LabelSSTRecord) record;
145. curRow = thisRow = lsrec.getRow();
146. thisColumn = lsrec.getColumn();
147. if (sstRecord == null) {
148. rowlist.add(thisColumn, " ");
149. } else {
150. value =  sstRecord
151. .getString(lsrec.getSSTIndex()).toString().trim();
152. value = value.equals("")?" ":value;
153. rowlist.add(thisColumn,value);
154. }
155. break;
156. case NumberRecord.sid:  //单元格为数字类型
157. NumberRecord numrec = (NumberRecord) record;
158. curRow = thisRow = numrec.getRow();
159. thisColumn = numrec.getColumn();
160. value = formatListener.formatNumberDateCell(numrec).trim();
161. value = value.equals("")?" ":value;
162. // 向容器加入列值
163. rowlist.add(thisColumn, value);
164. break;
165. default:
166. break;
167. }
168. // 遇到新行的操作
169. if (thisRow != -1 && thisRow != lastRowNumber) {
170. lastColumnNumber = -1;
171. }
172. // 空值的操作
173. if (record instanceof MissingCellDummyRecord) {
174. MissingCellDummyRecord mc = (MissingCellDummyRecord) record;
175. curRow = thisRow = mc.getRow();
176. thisColumn = mc.getColumn();
177. rowlist.add(thisColumn," ");
178. }
179. // 更新行和列的值
180. if (thisRow &gt; -1)
181. lastRowNumber = thisRow;
182. if (thisColumn &gt; -1)
183. lastColumnNumber = thisColumn;
184. // 行结束时的操作
185. if (record instanceof LastCellOfRowDummyRecord) {
186. if (minColumns &gt; 0) {
187. // 列值重新置空
188. if (lastColumnNumber == -1) {
189. lastColumnNumber = 0;
190. }
191. }
192. lastColumnNumber = -1;
193. // 每行结束时， 调用getRows() 方法
194. rowReader.getRows(sheetIndex,curRow, rowlist);
195. // 清空容器
196. rowlist.clear();
197. }
198. }
199. }

**\[java]** [view plain](http://blog.csdn.net/goodkuang2012/article/details/7350985 "view plain")[copy](http://blog.csdn.net/goodkuang2012/article/details/7350985 "copy")

 

001. /\**
002. * 抽象Excel2007读取器，excel2007的底层数据结构是xml文件，采用SAX的事件驱动的方法解析
003. * xml，需要继承DefaultHandler，在遇到文件内容时，事件会触发，这种做法可以大大降低
004. * 内存的耗费，特别使用于大数据量的文件。
005. \*
006. \*/
007. public class Excel2007Reader extends DefaultHandler {
008. //共享字符串表
009. private SharedStringsTable sst;
010. //上一次的内容
011. private String lastContents;
012. private boolean nextIsString;
013. private int sheetIndex = -1;
014. private List&lt;String&gt; rowlist = new ArrayList&lt;String&gt;();
015. //当前行
016. private int curRow = 0;
017. //当前列
018. private int curCol = 0;
019. //日期标志
020. private boolean dateFlag;
021. //数字标志
022. private boolean numberFlag;
023. private boolean isTElement;
024. private IRowReader rowReader;
025. public void setRowReader(IRowReader rowReader){
026. this.rowReader = rowReader;
027. }
028. /\*\*只遍历一个电子表格，其中sheetId为要遍历的sheet索引，从1开始，1-3
029. * @param filename
030. * @param sheetId
031. * @throws Exception
032. \*/
033. public void processOneSheet(String filename,int sheetId) throws Exception {
034. OPCPackage pkg = OPCPackage.open(filename);
035. XSSFReader r = new XSSFReader(pkg);
036. SharedStringsTable sst = r.getSharedStringsTable();
037. XMLReader parser = fetchSheetParser(sst);
038. // 根据 rId# 或 rSheet# 查找sheet
039. InputStream sheet2 = r.getSheet("rId"+sheetId);
040. sheetIndex++;
041. InputSource sheetSource = new InputSource(sheet2);
042. parser.parse(sheetSource);
043. sheet2.close();
044. }
045. /\**
046. * 遍历工作簿中所有的电子表格
047. * @param filename
048. * @throws Exception
049. \*/
050. public void process(String filename) throws Exception {
051. OPCPackage pkg = OPCPackage.open(filename);
052. XSSFReader r = new XSSFReader(pkg);
053. SharedStringsTable sst = r.getSharedStringsTable();
054. XMLReader parser = fetchSheetParser(sst);
055. Iterator&lt;InputStream&gt; sheets = r.getSheetsData();
056. while (sheets.hasNext()) {
057. curRow = 0;
058. sheetIndex++;
059. InputStream sheet = sheets.next();
060. InputSource sheetSource = new InputSource(sheet);
061. parser.parse(sheetSource);
062. sheet.close();
063. }
064. }
065. public XMLReader fetchSheetParser(SharedStringsTable sst)
066. throws SAXException {
067. XMLReader parser = XMLReaderFactory
068. .createXMLReader("org.apache.xerces.parsers.SAXParser");
069. this.sst = sst;
070. parser.setContentHandler(this);
071. return parser;
072. }
073. public void startElement(String uri, String localName, String name,
074. Attributes attributes) throws SAXException {
075. // c =&gt; 单元格
076. if ("c".equals(name)) {
077. // 如果下一个元素是 SST 的索引，则将nextIsString标记为true
078. String cellType = attributes.getValue("t");
079. if ("s".equals(cellType)) {
080. nextIsString = true;
081. } else {
082. nextIsString = false;
083. }
084. //日期格式
085. String cellDateType = attributes.getValue("s");
086. if ("1".equals(cellDateType)){
087. dateFlag = true;
088. } else {
089. dateFlag = false;
090. }
091. String cellNumberType = attributes.getValue("s");
092. if("2".equals(cellNumberType)){
093. numberFlag = true;
094. } else {
095. numberFlag = false;
096. }
097. }
098. //当元素为t时
099. if("t".equals(name)){
100. isTElement = true;
101. } else {
102. isTElement = false;
103. }
104. // 置空
105. lastContents = "";
106. }
107. public void endElement(String uri, String localName, String name)
108. throws SAXException {
109. // 根据SST的索引值的到单元格的真正要存储的字符串
110. // 这时characters()方法可能会被调用多次
111. if (nextIsString) {
112. try {
113. int idx = Integer.parseInt(lastContents);
114. lastContents = new XSSFRichTextString(sst.getEntryAt(idx))
115. .toString();
116. } catch (Exception e) {
117. }
118. }
119. //t元素也包含字符串
120. if(isTElement){
121. String value = lastContents.trim();
122. rowlist.add(curCol, value);
123. curCol++;
124. isTElement = false;
125. // v =&gt; 单元格的值，如果单元格是字符串则v标签的值为该字符串在SST中的索引
126. // 将单元格内容加入rowlist中，在这之前先去掉字符串前后的空白符
127. } else if ("v".equals(name)) {
128. String value = lastContents.trim();
129. value = value.equals("")?" ":value;
130. //日期格式处理
131. if(dateFlag){
132. Date date = HSSFDateUtil.getJavaDate(Double.valueOf(value));
133. SimpleDateFormat dateFormat = new SimpleDateFormat(
134. "dd/MM/yyyy");
135. value = dateFormat.format(date);
136. }
137. //数字类型处理
138. if(numberFlag){
139. BigDecimal bd = new BigDecimal(value);
140. value = bd.setScale(3,BigDecimal.ROUND\_UP).toString();
141. }
142. rowlist.add(curCol, value);
143. curCol++;
144. }else {
145. //如果标签名称为 row ，这说明已到行尾，调用 optRows() 方法
146. if (name.equals("row")) {
147. rowReader.getRows(sheetIndex,curRow,rowlist);
148. rowlist.clear();
149. curRow++;
150. curCol = 0;
151. }
152. }
153. }
154. public void characters(char\[] ch, int start, int length)
155. throws SAXException {
156. //得到单元格内容的值
157. lastContents += new String(ch, start, length);
158. }
159. }

**\[java]** [view plain](http://blog.csdn.net/goodkuang2012/article/details/7350985 "view plain")[copy](http://blog.csdn.net/goodkuang2012/article/details/7350985 "copy")

 

01. public class ExcelReaderUtil {
02. //excel2003扩展名
03. public static final String EXCEL03\_EXTENSION = ".xls";
04. //excel2007扩展名
05. public static final String EXCEL07\_EXTENSION = ".xlsx";
06. /\**
07. * 读取Excel文件，可能是03也可能是07版本
08. * @param excel03
09. * @param excel07
10. * @param fileName
11. * @throws Exception
12. \*/
13. public static void readExcel(IRowReader reader,String fileName) throws Exception{
14. // 处理excel2003文件
15. if (fileName.endsWith(EXCEL03\_EXTENSION)){
16. Excel2003Reader excel03 = new Excel2003Reader();
17. excel03.setRowReader(reader);
18. excel03.process(fileName);
19. // 处理excel2007文件
20. } else if (fileName.endsWith(EXCEL07\_EXTENSION)){
21. Excel2007Reader excel07 = new Excel2007Reader();
22. excel07.setRowReader(reader);
23. excel07.process(fileName);
24. } else {
25. throw new  Exception("文件格式错误，fileName的扩展名只能是xls或xlsx。");
26. }
27. }
28. }

**\[java]** [view plain](http://blog.csdn.net/goodkuang2012/article/details/7350985 "view plain")[copy](http://blog.csdn.net/goodkuang2012/article/details/7350985 "copy")

 

1. public interface IRowReader {
2. /\*\*业务逻辑实现方法
3. * @param sheetIndex
4. * @param curRow
5. * @param rowlist
6. \*/
7. public  void getRows(int sheetIndex,int curRow, List&lt;String&gt; rowlist);
8. }

**\[java]** [view plain](http://blog.csdn.net/goodkuang2012/article/details/7350985 "view plain")[copy](http://blog.csdn.net/goodkuang2012/article/details/7350985 "copy")

 

01. public class RowReader implements IRowReader{
02. /* 业务逻辑实现方法
03. * @see com.eprosun.util.excel.IRowReader#getRows(int, int, java.util.List)
04. \*/
05. public void getRows(int sheetIndex, int curRow, List&lt;String&gt; rowlist) {
06. // TODO Auto-generated method stub
07. System.out.print(curRow+" ");
08. for (int i = 0; i &lt; rowlist.size(); i++) {
09. System.out.print(rowlist.get(i) + " ");
10. }
11. System.out.println();
12. }
13. }

 

**\[java]** [view plain](http://blog.csdn.net/goodkuang2012/article/details/7350985 "view plain")[copy](http://blog.csdn.net/goodkuang2012/article/details/7350985 "copy")

 

1. public class Main {
2. public static void main(String\[] args) throws Exception {
3. IRowReader reader = new RowReader();
4. //ExcelReaderUtil.readExcel(reader, "F://te03.xls");
5. ExcelReaderUtil.readExcel(reader, "F://test07.xlsx");
6. }
7. }

**\[java]** [view plain](http://blog.csdn.net/goodkuang2012/article/details/7350985 "view plain")[copy](http://blog.csdn.net/goodkuang2012/article/details/7350985 "copy")

 

01. public class Excel2003Writer {
02. /\**
03. * @param args
04. \*/
05. public static void main(String\[] args) {
06. try{
07. System.out.println("开始写入excel2003....");
08. writeExcel("tes2003.xls");
09. System.out.println("写完xcel2003");
10. } catch (IOException e) {
11. }
12. }
13. /\**
14. * 写入excel并填充内容,一个sheet只能写65536行以下，超出会报异常，写入时建议使用AbstractExcel2007Writer
15. * @param fileName
16. * @throws IOException
17. \*/
18. public static void writeExcel(String fileName) throws IOException{
19. // 创建excel2003对象
20. Workbook wb = new HSSFWorkbook();
21. // 设置文件放置路径和文件名
22. FileOutputStream fileOut = new FileOutputStream(fileName);
23. // 创建新的表单
24. Sheet sheet = wb.createSheet("newsheet");
25. // 创建新行
26. for(int i=0;i&lt;20000;i++){
27. Row row = sheet.createRow(i);
28. // 创建单元格
29. Cell cell = row.createCell(0);
30. // 设置单元格值
31. cell.setCellValue(1);
32. row.createCell(1).setCellValue(1+i);
33. row.createCell(2).setCellValue(true);
34. row.createCell(3).setCellValue(0.43d);
35. row.createCell(4).setCellValue('d');
36. row.createCell(5).setCellValue("");
37. row.createCell(6).setCellValue("第七列"+i);
38. row.createCell(7).setCellValue("第八列"+i);
39. }
40. wb.write(fileOut);
41. fileOut.close();
42. }
43. }

```

```

**\[java]** [view plain](http://blog.csdn.net/goodkuang2012/article/details/7350985 "view plain")[copy](http://blog.csdn.net/goodkuang2012/article/details/7350985 "copy")

 

001. /\**
002. * 抽象excel2007读入器，先构建.xlsx一张模板，改写模板中的sheet.xml,使用这种方法
003. * 写入.xlsx文件，不需要太大的内存
004. \*
005. \*/
006. public abstract class AbstractExcel2007Writer {
007. private SpreadsheetWriter sw;
008. /\**
009. * 写入电子表格的主要流程
010. * @param fileName
011. * @throws Exception
012. \*/
013. public void process(String fileName) throws Exception{
014. // 建立工作簿和电子表格对象
015. XSSFWorkbook wb = new XSSFWorkbook();
016. XSSFSheet sheet = wb.createSheet("sheet1");
017. // 持有电子表格数据的xml文件名 例如 /xl/worksheets/sheet1.xml
018. String sheetRef = sheet.getPackagePart().getPartName().getName();
019. // 保存模板
020. FileOutputStream os = new FileOutputStream("template.xlsx");
021. wb.write(os);
022. os.close();
023. // 生成xml文件
024. File tmp = File.createTempFile("sheet", ".xml");
025. Writer fw = new FileWriter(tmp);
026. sw = new SpreadsheetWriter(fw);
027. generate();
028. fw.close();
029. // 使用产生的数据替换模板
030. File templateFile = new File("template.xlsx");
031. FileOutputStream out = new FileOutputStream(fileName);
032. substitute(templateFile, tmp, sheetRef.substring(1), out);
033. out.close();
034. //删除文件之前调用一下垃圾回收器，否则无法删除模板文件
035. System.gc();
036. // 删除临时模板文件
037. if (templateFile.isFile()&&templateFile.exists()){
038. templateFile.delete();
039. }
040. }
041. /\**
042. * 类使用者应该使用此方法进行写操作
043. * @throws Exception
044. \*/
045. public abstract void generate() throws Exception;
046. public void beginSheet() throws IOException {
047. sw.beginSheet();
048. }
049. public void insertRow(int rowNum) throws IOException {
050. sw.insertRow(rowNum);
051. }
052. public void createCell(int columnIndex, String value) throws IOException {
053. sw.createCell(columnIndex, value, -1);
054. }
055. public void createCell(int columnIndex, double value) throws IOException {
056. sw.createCell(columnIndex, value, -1);
057. }
058. public void endRow() throws IOException {
059. sw.endRow();
060. }
061. public void endSheet() throws IOException {
062. sw.endSheet();
063. }
064. /\**
065. \*
066. * @param zipfile the template file
067. * @param tmpfile the XML file with the sheet data
068. * @param entry the name of the sheet entry to substitute, e.g. xl/worksheets/sheet1.xml
069. * @param out the stream to write the result to
070. \*/
071. private static void substitute(File zipfile, File tmpfile, String entry,
072. OutputStream out) throws IOException {
073. ZipFile zip = new ZipFile(zipfile);
074. ZipOutputStream zos = new ZipOutputStream(out);
075. @SuppressWarnings("unchecked")
076. Enumeration&lt;ZipEntry&gt; en = (Enumeration&lt;ZipEntry&gt;) zip.entries();
077. while (en.hasMoreElements()) {
078. ZipEntry ze = en.nextElement();
079. if (!ze.getName().equals(entry)) {
080. zos.putNextEntry(new ZipEntry(ze.getName()));
081. InputStream is = zip.getInputStream(ze);
082. copyStream(is, zos);
083. is.close();
084. }
085. }
086. zos.putNextEntry(new ZipEntry(entry));
087. InputStream is = new FileInputStream(tmpfile);
088. copyStream(is, zos);
089. is.close();
090. zos.close();
091. }
092. private static void copyStream(InputStream in, OutputStream out)
093. throws IOException {
094. byte\[] chunk = new byte\[1024];
095. int count;
096. while ((count = in.read(chunk)) &gt;= 0) {
097. out.write(chunk, 0, count);
098. }
099. }
100. /\**
101. * 在写入器中写入电子表格
102. \*
103. \*/
104. public static class SpreadsheetWriter {
105. private final Writer \_out;
106. private int \_rownum;
107. private static String LINE\_SEPARATOR = System.getProperty("line.separator");
108. public SpreadsheetWriter(Writer out) {
109. \_out = out;
110. }
111. public void beginSheet() throws IOException {
112. \_out.write("&lt;?xml version=\\"1.0\\" encoding=\\"GB2312\\"?&gt;"
113. + "&lt;worksheet xmlns=\\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\\"&gt;");
114. \_out.write("&lt;sheetData&gt;"+LINE\_SEPARATOR);
115. }
116. public void endSheet() throws IOException {
117. \_out.write("&lt;/sheetData&gt;");
118. \_out.write("&lt;/worksheet&gt;");
119. }
120. /\**
121. * 插入新行
122. \*
123. * @param rownum 以0开始
124. \*/
125. public void insertRow(int rownum) throws IOException {
126. \_out.write("&lt;row r=\\"" + (rownum + 1) + "\\"&gt;"+LINE\_SEPARATOR);
127. this.\_rownum = rownum;
128. }
129. /\**
130. * 插入行结束标志
131. \*/
132. public void endRow() throws IOException {
133. \_out.write("&lt;/row&gt;"+LINE\_SEPARATOR);
134. }
135. /\**
136. * 插入新列
137. * @param columnIndex
138. * @param value
139. * @param styleIndex
140. * @throws IOException
141. \*/
142. public void createCell(int columnIndex, String value, int styleIndex)
143. throws IOException {
144. String ref = new CellReference(\_rownum, columnIndex)
145. .formatAsString();
146. \_out.write("&lt;c r=\\"" + ref + "\\" t=\\"inlineStr\\"");
147. if (styleIndex != -1)
148. \_out.write(" s=\\"" + styleIndex + "\\"");
149. \_out.write("&gt;");
150. \_out.write("&lt;is&gt;&lt;t&gt;"+XMLEncoder.encode(value)+"&lt;/t&gt;&lt;/is&gt;");
151. \_out.write("&lt;/c&gt;");
152. }
153. public void createCell(int columnIndex, String value)
154. throws IOException {
155. createCell(columnIndex, value, -1);
156. }
157. public void createCell(int columnIndex, double value, int styleIndex)
158. throws IOException {
159. String ref = new CellReference(\_rownum, columnIndex)
160. .formatAsString();
161. \_out.write("&lt;c r=\\"" + ref + "\\" t=\\"n\\"");
162. if (styleIndex != -1)
163. \_out.write(" s=\\"" + styleIndex + "\\"");
164. \_out.write("&gt;");
165. \_out.write("&lt;v&gt;" + value + "&lt;/v&gt;");
166. \_out.write("&lt;/c&gt;");
167. }
168. public void createCell(int columnIndex, double value)
169. throws IOException {
170. createCell(columnIndex, value, -1);
171. }
172. public void createCell(int columnIndex, Calendar value, int styleIndex)
173. throws IOException {
174. createCell(columnIndex, DateUtil.getExcelDate(value, false),
175. styleIndex);
176. }
177. }
178. }

 

**\[java]** [view plain](http://blog.csdn.net/goodkuang2012/article/details/7350985 "view plain")[copy](http://blog.csdn.net/goodkuang2012/article/details/7350985 "copy")

 

01. public class Excel2007WriterImpl extends AbstractExcel2007Writer{
02. /\**
03. * @param args
04. * @throws Exception
05. \*/
06. public static void main(String\[] args) throws Exception {
07. // TODO Auto-generated method stub
08. System.out.println("............................");
09. long start = System.currentTimeMillis();
10. //构建excel2007写入器
11. AbstractExcel2007Writer excel07Writer = new Excel2007WriterImpl();
12. //调用处理方法
13. excel07Writer.process("F://test07.xlsx");
14. long end = System.currentTimeMillis();
15. System.out.println("....................."+(end-start)/1000);
16. }
17. /*
18. * 可根据需求重写此方法，对于单元格的小数或者日期格式，会出现精度问题或者日期格式转化问题，建议使用字符串插入方法
19. * @see com.excel.ver2.AbstractExcel2007Writer#generate()
20. \*/
21. @Override
22. public void generate()throws Exception {
23. //电子表格开始
24. beginSheet();
25. for (int rownum = 0; rownum &lt; 100; rownum++) {
26. //插入新行
27. insertRow(rownum);
28. //建立新单元格,索引值从0开始,表示第一列
29. createCell(0, "中国&lt;" + rownum + "!");
30. createCell(1, 34343.123456789);
31. createCell(2, "23.67%");
32. createCell(3, "12:12:23");
33. createCell(4, "2010-10-11 12:12:23");
34. createCell(5, "true");
35. createCell(6, "false");
36. //结束行
37. endRow();
38. }
39. //电子表格结束
40. endSheet();
41. }
42. }

**\[java]** [view plain](http://blog.csdn.net/goodkuang2012/article/details/7350985 "view plain")[copy](http://blog.csdn.net/goodkuang2012/article/details/7350985 "copy")

 

01. public class XMLEncoder {
02. private static final String\[] xmlCode = new String\[256];
03. static {
04. // Special characters
05. xmlCode\['\\''] = "'";
06. xmlCode\['\\"'] = """; // double quote
07. xmlCode\['&'] = "&"; // ampersand
08. xmlCode\['&lt;'] = "&lt;"; // lower than
09. xmlCode\['&gt;'] = "&gt;"; // greater than
10. }
11. /\**
12. * &lt;p&gt;
13. * Encode the given text into xml.
14. * &lt;/p&gt;
15. \*
16. * @param string the text to encode
17. * @return the encoded string
18. \*/
19. public static String encode(String string) {
20. if (string == null) return "";
21. int n = string.length();
22. char character;
23. String xmlchar;
24. StringBuffer buffer = new StringBuffer();
25. // loop over all the characters of the String.
26. for (int i = 0; i &lt; n; i++) {
27. character = string.charAt(i);
28. // the xmlcode of these characters are added to a StringBuffer one by one
29. try {
30. xmlchar = xmlCode\[character];
31. if (xmlchar == null) {
32. buffer.append(character);
33. } else {
34. buffer.append(xmlCode\[character]);
35. }
36. } catch (ArrayIndexOutOfBoundsException aioobe) {
37. buffer.append(character);
38. }
39. }
40. return buffer.toString();
41. }
42. }