一、什么是Apache POI? 用来做什么?
poi: 是允许程序员使用java程序创建、修改和显示 Microsoft office文件的API,他包含了类和方法对用户输入数据和文件到Microsoft office文档进行解码。
二、在java程序中是用POI:
我这里是使用了spring boot + maven+idea进行一个maven项目的创建,如果是使用eclipse创建的java项目,直接网上下载POI的依赖jar包导入到项目中就可以了;
1、在pom.xml文件中添加POI依赖
<!-- 添加poi依赖操作Excel-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
2、将数据库中的数据根据自己需要生成Excel文件并保存到指定位置。
import org.apache.poi.hssf.usermodel.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.List;
/**
* 读取数据库数据生成excel
* @creat 2017/12/22
*/
public class ExcelUtil {
/**
* 设置表头,填充单元格
* @param tableName Excel的文件名称
* @param columns 字段名称
* @param datas 数据库数据(List里的一个对象就是数据库的一行记录)
* @return Excel对象
*/
private static HSSFWorkbook createExcel(String tableName,List<String> columns,List<Object> datas) throws Exception {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(tableName);
//设置单元格样式style(居中加粗自动换行)
HSSFCellStyle style = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
font.setBold(true);//加粗
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//居中
style.setWrapText(true);//自动换行
style.setFont(font);
//表头
HSSFRow row = sheet.createRow(0);
int columnLength = columns.size();
for (int i=0;i<columnLength;i++){
sheet.setColumnWidth(i,15*256);//设置表头的列宽
row.createCell(i).setCellValue(columns.get(i));
}
//填充单元格
int dataLength = datas.size();
for (int i=0;i<dataLength;i++){
row = sheet.createRow(i+1);//第一行是表头 数据填充从第二行开始
for (int j=0;j<columnLength;j++){
row.createCell(j).setCellValue(JsonUtil.getString(columns.get(j),datas.get(i)));
}
}
return workbook;
}
/**
* 将数据库的数据生成指定位置的Excel表,且表名是自定义的
* @param excelName Excel文件名称
* @param datas 数据库数据
* @return excel 文件生成路径
*/
public static String create(String excelName, List<String> columns, List<Object> datas){
//获取程序当前路径
File directory = new File(System.getProperty("user.dir")+File.separator+"excelDownload");
if (!directory.exists()){
directory.mkdir();
}
File file = new File(directory.getPath()+File.separator+excelName+".xls");
try {
FileOutputStream out = new FileOutputStream(file);
createExcel(excelName,columns,datas).write(out);
return file.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
}
3、下载生成的Excel文件
@RestController
@RequestMapping("util")
public class UtilController {
@RequestMapping(value = "downExcel",method = RequestMethod.GET)
//@ApiOperation(value = "下载Excel",notes = "下载Excel")
public String downExcel(HttpServletResponse response,@RequestParam("fileName") String fileName){
BufferedInputStream bfs = null;
OutputStream out = null;
try {
String filaName = filePath.substring(filePath.lastIndexOf("\\")+1);
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + filaName);
byte[] buff = new byte[1024];
try {
out = response.getOutputStream();
bfs = new BufferedInputStream(new FileInputStream(filePath));
int len = bfs.read(buff);
while (len != -1) {
out.write(buff, 0, buff.length);
out.flush();
len = bfs.read(buff);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bfs != null) {
try {
bfs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("文件下载成功");
}catch (Exception e){
e.printStackTrace();
}
return "成功";
}
}
4、运行项目打开浏览器输入(根据你自己的下载文件接口和生成的文件名称)
http://ip:ipport/util/downExcel?fileName=XXX.xls