1 .导入包
<!-- poi支持的jar包 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.11</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.11</version>
</dependency>
2写一个简单的99乘法表
@Test
public void testName() throws Exception{
//1.创建一个Excel文件(内存中)
XSSFWorkbook xSSFWorkbook = new XSSFWorkbook();
//创建表名
Sheet sheet = xSSFWorkbook.createSheet("99乘法表");
//创建行
for (int i = 1;i <= 9;i++){
Row row = sheet.createRow(i-1);
//创建列
for (int j =1;j <= i;j++) {
Cell cell = row.createCell(j-1);
//5.格子中加数据
cell.setCellValue(j+"*"+i+"="+(i*j));
}
}
//从内存中写出来
FileOutputStream fileOutputStream = new FileOutputStream("99乘法表.xlsx");
xSSFWorkbook.write(fileOutputStream);
fileOutputStream.close();
}
3读取Excel
准备一个xlsx 文件
//导入表格
@Test
public void testName1() throws Exception{
FileInputStream fileInputStream = new FileInputStream(new File("empread.xlsx"));
//1.得到工作薄
XSSFWorkbook xssfSheets = new XSSFWorkbook(fileInputStream);
//2.拿到第个sheet表
XSSFSheet sheetAt = xssfSheets.getSheetAt(0);
//3.拿到wb中的行(不要拿头部)
int lastRowNum = sheetAt.getLastRowNum();
for (int i = 1;i<lastRowNum;i++){
XSSFRow row = sheetAt.getRow(i);
short lastCellNum = row.getLastCellNum();
for (int j =0;j<lastCellNum;j++){
XSSFCell cell = row.getCell(j);
System.out.print(cell.getStringCellValue()+" ");
}
System.out.println( );
}
}
4._SpringMVC导出功能
在展示数据的页面 加入一个导出按钮
<a href="/employee/download " class="easyui-linkbutton" iconCls="icon-redo" plain="true">导出</a>
@RequestMapping("/download")
public void download(HttpServletResponse response) throws Exception{
//准备下载的文件名
String filename = "employee.xlsx";
response.setHeader("Content-disposition", filename);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); //mime类型
response.setHeader("Content-disposition", "attachment;filename="+filename);
response.setHeader("Pragma", "No-cache");
//1.创建一个Excel文件(内存中)
SXSSFWorkbook wb = new SXSSFWorkbook();
//2.创建一张表
Sheet sheet = wb.createSheet("99乘法表");
//3.创建行
for (int i = 1; i <= 9; i++) {
Row row = sheet.createRow(i-1);
//4.创建列(格子)
for (int j = 1; j &l