首先感谢阿里巴巴提供了easyexcel工具类,github地址:https://github.com/alibaba/easyexcel
注意!!这里只是一个简单的示例,VC大法即可使用,对于复杂的execl导出可能会出现问题。
另Execl文件后缀为xlsx。
1、环境搭建
jar包依赖
<!-- excel导入导出插件 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>1.1.2-beat1</version>
</dependency>
2、代码
public class MyExcel {
//读
@Test
public void simpleRead() {
FileInputStream fileInput;
try {
fileInput = new FileInputStream("F://javaio文件目录//hss.xlsx");
List<Object> read = EasyExcelFactory.read(fileInput, new Sheet(0,0));
System.out.println(read);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//写
@Test
public void simpleWrite() {
FileOutputStream fileOut;
try {
File file = new File("F://javaio文件目录//hss123.xlsx");
if (file.exists()) {
file.delete();
}
fileOut=new FileOutputStream("F://javaio文件目录//hss123.xlsx");
ExcelWriter writer = EasyExcelFactory.getWriter(fileOut);
Sheet sheet = new Sheet(1,0);
Sheet sheet2 = new Sheet(1,0);
sheet.setSheetName("HelloWord");
List<List<String>> data2 = new ArrayList<>();
List<String> list2 = new ArrayList<>();
List<String> list3 = new ArrayList<>();
List<String> list4 = new ArrayList<>();
List<String> list5 = new ArrayList<>();
List<List<String>> data = new ArrayList<>();
List<String> list1 = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list1.add("123");
list1.add("123");
list1.add("123");
list1.add("123");
list1.add("123");
data.add(list1);
}
list2.add("你好1");
list3.add("你好2");
list4.add("你好3");
list5.add("你好4");
data2.add(list2);
data2.add(list3);
data2.add(list4);
data2.add(list5);
sheet2.setHead(data2);
writer.write0(null, sheet2);
writer.write0(data, sheet);
writer.finish();
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
来源:oschina
链接:https://my.oschina.net/u/4327970/blog/3337532