Browse Source

修复前面7月20日前提到的bug

bugfix
jipengfei.jpf 6 years ago
parent
commit
891c620a41
  1. 2
      pom.xml
  2. 4
      src/main/java/com/alibaba/excel/ExcelWriter.java
  3. 40
      src/main/java/com/alibaba/excel/read/SaxAnalyserV07.java
  4. 12
      src/main/java/com/alibaba/excel/read/v07/XmlParserFactory.java
  5. 15
      src/main/java/com/alibaba/excel/util/FileUtil.java
  6. 144
      src/main/java/com/alibaba/excel/util/IndexValueConverter.java
  7. 103
      src/test/java/javamodel/ExcelRowJavaModel1.java
  8. 44
      src/test/java/read/v07/Read2007Xlsx.java
  9. BIN
      src/test/resources/2007NoModelMultipleSheet.xlsx
  10. BIN
      src/test/resources/2007_1.xlsx
  11. BIN
      src/test/resources/77.xlsx
  12. BIN
      src/test/resources/sss.xlsx

2
pom.xml

@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId> <artifactId>easyexcel</artifactId>
<version>1.0.1</version> <version>1.0.2</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>easyexcel</name> <name>easyexcel</name>
<description>easyexcel is a excel handle tools written in Java</description> <description>easyexcel is a excel handle tools written in Java</description>

4
src/main/java/com/alibaba/excel/ExcelWriter.java

@ -20,7 +20,7 @@ public class ExcelWriter {
private ExcelBuilder excelBuilder; private ExcelBuilder excelBuilder;
/** /**
* 生成小Excel低于2000行 * 生成EXCEL
* *
* @param outputStream 文件输出流 * @param outputStream 文件输出流
* @param typeEnum 输出文件类型03或07强烈建议使用07版可以输出超大excel而不内存溢出 * @param typeEnum 输出文件类型03或07强烈建议使用07版可以输出超大excel而不内存溢出
@ -30,7 +30,7 @@ public class ExcelWriter {
} }
/** /**
* 生成小Excel低于2000行 * 生成EXCEL
* *
* @param outputStream 文件输出流 * @param outputStream 文件输出流
* @param typeEnum 输出文件类型03或07强烈建议使用07版可以输出超大excel而不内存溢出 * @param typeEnum 输出文件类型03或07强烈建议使用07版可以输出超大excel而不内存溢出

40
src/main/java/com/alibaba/excel/read/SaxAnalyserV07.java

@ -84,6 +84,7 @@ public class SaxAnalyserV07 extends BaseSaxAnalyser {
stop(); stop();
throw new ExcelAnalysisException(e); throw new ExcelAnalysisException(e);
} finally { } finally {
} }
} }
@ -99,6 +100,16 @@ public class SaxAnalyserV07 extends BaseSaxAnalyser {
} }
public void stop() { public void stop() {
for (SheetSource sheet : sheetSourceList) {
if (sheet.getInputStream() != null) {
try {
sheet.getInputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileUtil.deletefile(path); FileUtil.deletefile(path);
} }
@ -164,16 +175,18 @@ public class SaxAnalyserV07 extends BaseSaxAnalyser {
this.sheetSourceList = new ArrayList<SheetSource>(); this.sheetSourceList = new ArrayList<SheetSource>();
InputStream workbookXml = new FileInputStream(this.workBookXMLFilePath); InputStream workbookXml = new FileInputStream(this.workBookXMLFilePath);
XmlParserFactory.parse(workbookXml, new DefaultHandler() { XmlParserFactory.parse(workbookXml, new DefaultHandler() {
private int id = 0;
@Override @Override
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
if (qName.toLowerCase(Locale.US).equals("sheet")) { if (qName.toLowerCase(Locale.US).equals("sheet")) {
String name = null; String name = null;
int id = 0; id++;
for (int i = 0; i < attrs.getLength(); i++) { for (int i = 0; i < attrs.getLength(); i++) {
if (attrs.getLocalName(i).toLowerCase(Locale.US).equals("name")) { if (attrs.getLocalName(i).toLowerCase(Locale.US).equals("name")) {
name = attrs.getValue(i); name = attrs.getValue(i);
} else if (attrs.getLocalName(i).toLowerCase(Locale.US).equals("r:id")) { } else if (attrs.getLocalName(i).toLowerCase(Locale.US).equals("r:id")) {
id = Integer.parseInt(attrs.getValue(i).replaceAll("rId", "")); //id = Integer.parseInt(attrs.getValue(i).replaceAll("rId", ""));
try { try {
InputStream inputStream = new FileInputStream(XMLTempFile.getSheetFilePath(path, id)); InputStream inputStream = new FileInputStream(XMLTempFile.getSheetFilePath(path, id));
sheetSourceList.add(new SheetSource(id, name, inputStream)); sheetSourceList.add(new SheetSource(id, name, inputStream));
@ -210,9 +223,28 @@ public class SaxAnalyserV07 extends BaseSaxAnalyser {
//this.sharedStringsTable.readFrom(inputStream); //this.sharedStringsTable.readFrom(inputStream);
XmlParserFactory.parse(inputStream, new DefaultHandler() { XmlParserFactory.parse(inputStream, new DefaultHandler() {
int lastElementPosition = -1;
int lastHandledElementPosition = -1;
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) {
if (hasSkippedEmptySharedString()) {
sharedStringList.add("");
}
if ("t".equals(qName)) {
lastElementPosition++;
}
}
private boolean hasSkippedEmptySharedString() {
return lastElementPosition > lastHandledElementPosition;
}
@Override @Override
public void characters(char[] ch, int start, int length) { public void characters(char[] ch, int start, int length) {
sharedStringList.add(new String(ch, start, length)); sharedStringList.add(new String(ch, start, length));
lastHandledElementPosition++;
} }
}); });
@ -261,9 +293,9 @@ public class SaxAnalyserV07 extends BaseSaxAnalyser {
if (o.id == this.id) { if (o.id == this.id) {
return 0; return 0;
} else if (o.id > this.id) { } else if (o.id > this.id) {
return 1;
} else {
return -1; return -1;
} else {
return 1;
} }
} }
} }

12
src/main/java/com/alibaba/excel/read/v07/XmlParserFactory.java

@ -18,10 +18,22 @@ import org.xml.sax.XMLReader;
*/ */
public class XmlParserFactory { public class XmlParserFactory {
/**
* xml解析
* @param inputStream
* @param contentHandler
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
*/
public static void parse(InputStream inputStream, ContentHandler contentHandler) public static void parse(InputStream inputStream, ContentHandler contentHandler)
throws ParserConfigurationException, SAXException, IOException { throws ParserConfigurationException, SAXException, IOException {
InputSource sheetSource = new InputSource(inputStream); InputSource sheetSource = new InputSource(inputStream);
SAXParserFactory saxFactory = SAXParserFactory.newInstance(); SAXParserFactory saxFactory = SAXParserFactory.newInstance();
//防止XML实体注注入
saxFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
saxFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
saxFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
SAXParser saxParser = saxFactory.newSAXParser(); SAXParser saxParser = saxFactory.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader(); XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(contentHandler); xmlReader.setContentHandler(contentHandler);

15
src/main/java/com/alibaba/excel/util/FileUtil.java

@ -66,12 +66,23 @@ public class FileUtil {
return (filePosi == -1) ? "" : filePath.substring(0, filePosi); return (filePosi == -1) ? "" : filePath.substring(0, filePosi);
} }
/**
* 文件解压
* @param path
* @param file
* @return
* @throws IOException
*/
public static boolean doUnZip(String path, File file) throws IOException { public static boolean doUnZip(String path, File file) throws IOException {
ZipFile zipFile = new ZipFile(file, "utf-8"); ZipFile zipFile = new ZipFile(file, "utf-8");
Enumeration<ZipArchiveEntry> en = zipFile.getEntries(); Enumeration<ZipArchiveEntry> en = zipFile.getEntries();
ZipArchiveEntry ze; ZipArchiveEntry ze;
while (en.hasMoreElements()) { while (en.hasMoreElements()) {
ze = en.nextElement(); ze = en.nextElement();
if(ze.getName().contains("../")){
//防止目录穿越
throw new IllegalStateException("unsecurity zipfile!");
}
File f = new File(path, ze.getName()); File f = new File(path, ze.getName());
if (ze.isDirectory()) { if (ze.isDirectory()) {
f.mkdirs(); f.mkdirs();
@ -103,11 +114,9 @@ public class FileUtil {
deletefile(delpath + File.separator + filelist[i]); deletefile(delpath + File.separator + filelist[i]);
} }
} }
file.delete();
} }
} }
public static void main(String[] args) {
System.out.println(File.separator);
}
} }

144
src/main/java/com/alibaba/excel/util/IndexValueConverter.java

@ -1,73 +1,71 @@
package com.alibaba.excel.util; //package com.alibaba.excel.util;
//
import java.util.ArrayList; //import java.util.ArrayList;
import java.util.List; //import java.util.List;
import java.util.Stack; //import java.util.Stack;
//
import com.alibaba.excel.metadata.IndexValue; //import com.alibaba.excel.metadata.IndexValue;
//
/** ///**
* 去除空Cell // * 去除空Cell
* @author jipengfei // * @author jipengfei
*/ // */
public class IndexValueConverter { //public class IndexValueConverter {
public static List<String> converter(List<IndexValue> i_list) { // public static List<String> converter(List<IndexValue> i_list) {
//
List<String> tem = new ArrayList<String>(); // List<String> tem = new ArrayList<String>();
//
char[] start = {'@'}; // char[] start = {'@'};
int j = 0; // int j = 0;
for (; j < i_list.size(); j++) { // for (; j < i_list.size(); j++) {
IndexValue currentIndexValue = i_list.get(j); // IndexValue currentIndexValue = i_list.get(j);
char[] currentIndex = currentIndexValue.getV_index().replaceAll("[0-9]", "").toCharArray(); // char[] currentIndex = currentIndexValue.getV_index().replaceAll("[0-9]", "").toCharArray();
if (j > 0) { // if (j > 0) {
start = i_list.get(j - 1).getV_index().replaceAll("[0-9]", "").toCharArray(); // start = i_list.get(j - 1).getV_index().replaceAll("[0-9]", "").toCharArray();
} // }
int deep = subtraction26(currentIndex, start); // int deep = subtraction26(currentIndex, start);
int k = 0; // int k = 0;
for (; k < deep - 1; k++) { // for (; k < deep - 1; k++) {
tem.add(null); // tem.add(null);
} // }
tem.add(currentIndexValue.getV_value()); // tem.add(currentIndexValue.getV_value());
} // }
return tem; // return tem;
} // }
//
private static int subtraction26(char[] currentIndex, char[] beforeIndex) { // private static int subtraction26(char[] currentIndex, char[] beforeIndex) {
int result = 0; // int result = 0;
//
Stack<Character> currentStack = new Stack<Character>(); // Stack<Character> currentStack = new Stack<Character>();
Stack<Character> berforStack = new Stack<Character>(); // Stack<Character> beforeStack = new Stack<Character>();
//
for (int i = 0; i < currentIndex.length; i++) { // for (int i = 0; i < currentIndex.length; i++) {
currentStack.push(currentIndex[i]); // currentStack.push(currentIndex[i]);
} // }
for (int i = 0; i < beforeIndex.length; i++) { // for (int i = 0; i < beforeIndex.length; i++) {
berforStack.push(beforeIndex[i]); // beforeStack.push(beforeIndex[i]);
} // }
int i = 0; // int i = 0;
char beforechar = '@'; // char beforeChar = '@';
while (!currentStack.isEmpty()) { // while (!currentStack.isEmpty()) {
char currentChar = currentStack.pop(); // char currentChar = currentStack.pop();
if (!berforStack.isEmpty()) { // if (!beforeStack.isEmpty()) {
beforechar = berforStack.pop(); // beforeChar = beforeStack.pop();
} // }
int n = currentChar - beforechar; // int n = currentChar - beforeChar;
if(n<0){ // if(n<0){
n = n+26; // n = n+26;
if(!currentStack.isEmpty()){ // if(!currentStack.isEmpty()){
char borrow = currentStack.pop(); // char borrow = currentStack.pop();
char newBorrow =(char)(borrow -1); // char newBorrow =(char)(borrow -1);
currentStack.push(newBorrow); // currentStack.push(newBorrow);
} // }
} // }
// result += n * Math.pow(26, i);
// i++;
result += n * Math.pow(26, i); // beforeChar='@';
i++; // }
beforechar='@'; //
} // return result;
// }
return result; //}
}
}

103
src/test/java/javamodel/ExcelRowJavaModel1.java

@ -14,117 +14,32 @@ import com.alibaba.excel.metadata.BaseRowModel;
public class ExcelRowJavaModel1 extends BaseRowModel { public class ExcelRowJavaModel1 extends BaseRowModel {
@ExcelProperty(index = 0,value = "银行放款编号") @ExcelProperty(index = 0,value = "银行放款编号")
private int num; private String num;
@ExcelProperty(index = 1,value = "code") @ExcelProperty(index = 1,value = "code")
private Long code; private String code;
@ExcelProperty(index = 2,value = "银行存放期期") public String getNum() {
private Date endTime;
@ExcelProperty(index = 3,value = "测试1")
private Double money;
@ExcelProperty(index = 4,value = "测试2")
private String times;
@ExcelProperty(index = 5,value = "测试3")
private int activityCode;
@ExcelProperty(index = 6,value = "测试4")
private Date date;
@ExcelProperty(index = 7,value = "测试5")
private Double lx;
@ExcelProperty(index = 8,value = "测试6")
private String name;
public int getNum() {
return num; return num;
} }
public void setNum(int num) { public void setNum(String num) {
this.num = num; this.num = num;
} }
public Long getCode() { public String getCode() {
return code; return code;
} }
public void setCode(Long code) { public void setCode(String code) {
this.code = code; this.code = code;
} }
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
public String getTimes() {
return times;
}
public void setTimes(String times) {
this.times = times;
}
public int getActivityCode() {
return activityCode;
}
public void setActivityCode(int activityCode) {
this.activityCode = activityCode;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Double getLx() {
return lx;
}
public void setLx(Double lx) {
this.lx = lx;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override @Override
public String toString() { public String toString() {
return "ExcelRowJavaModel{" + return "ExcelRowJavaModel1{" +
"num=" + num + "num='" + num + '\'' +
", code=" + code + ", code='" + code + '\'' +
", endTime=" + endTime +
", money=" + money +
", times='" + times + '\'' +
", activityCode=" + activityCode +
", date=" + date +
", lx=" + lx +
", name='" + name + '\'' +
'}'; '}';
} }
} }

44
src/test/java/read/v07/Read2007Xlsx.java

@ -107,6 +107,7 @@ public class Read2007Xlsx {
}); });
reader.read(); reader.read();
//reader.finish();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -161,6 +162,49 @@ public class Read2007Xlsx {
} }
} }
@Test
public void withModelMultipleSheet1() {
InputStream inputStream = getInputStream("sss.xlsx");
try {
ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null,
new AnalysisEventListener() {
@Override
public void invoke(Object object, AnalysisContext context) {
ExcelRowJavaModel1 obj = null;
if (context.getCurrentSheet().getSheetNo() == 1) {
obj = (ExcelRowJavaModel1)object;
}
//if (context.getCurrentSheet().getSheetNo() == 2) {
// obj = (ExcelRowJavaModel)object;
//}
System.out.println(
"当前sheet:" + context.getCurrentSheet().getSheetNo() + " 当前行:" + context.getCurrentRowNum()
+ " data:" + obj);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
}
});
reader.read(new Sheet(1, 1, ExcelRowJavaModel1.class));
// reader.read(new Sheet(2, 1, ExcelRowJavaModel1.class));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//读取shets //读取shets
@Test @Test
public void getSheets() { public void getSheets() {

BIN
src/test/resources/2007NoModelMultipleSheet.xlsx

Binary file not shown.

BIN
src/test/resources/2007_1.xlsx

Binary file not shown.

BIN
src/test/resources/77.xlsx

Binary file not shown.

BIN
src/test/resources/sss.xlsx

Binary file not shown.
Loading…
Cancel
Save