最近老是用到导出功能,用别人写的工具类贼不爽,于是自己写了一个。
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</dependency>
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
/**
* @author lianghuadong
* @version 1.0-SNAPSHOT
* @company
* @description
* @jdk-v 1.8.0_161
* @date 2019/3/29 15:25
* @update
*/
public class MyExportExcelUtil {
/**
* 1.数据转化一步比较麻烦 所以把数据转化这一步放到外面去解决,
* 2.Excel文件的格式设置也比较麻烦 所以一步直接写死。OK
*
* @param response
* @param fileName
* @param lst
* @param names
* @param sheetName
* @throws Exception
*/
public static void exportMyExcel(HttpServletResponse response, String fileName, List<List<String>> lst, List<String> names, String sheetName ) throws Exception {
// 告诉浏览器用什么软件可以打开此文件
response.setHeader("content-Type", "application/vnd.ms-excel");
// 下载文件的默认名称
response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "utf-8"));
exportMyExcel(lst,names,sheetName, response.getOutputStream());
}
public static void exportMyExcel(List<List<String>> lst,List<String> names,String sheetName , OutputStream out) throws Exception {
XSSFWorkbook wb = new XSSFWorkbook();
try {
if (null == sheetName) {
sheetName = "Sheet1";
}
XSSFSheet sheet = wb.createSheet(sheetName);
writeMyExcel(wb, sheet, lst,names);
wb.write(out);
} finally {
wb.close();
}
}
private static Cell createMyCell(XSSFWorkbook wb, Row row, int index) {
XSSFCellStyle style = wb.createCellStyle();
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
Cell cell = row.createCell(index);
cell.setCellStyle(style);
return cell;
}
private static void writeMyExcel(XSSFWorkbook wb, Sheet sheet, List<List<String>> lst, List<String> names) {
Row row = sheet.createRow(0);
//设置首行
for (int i = 0; i < names.size(); i++) {
createMyCell(wb,row,i).setCellValue(names.get(i));
}
//设置其他行
for (int j = 0; j <lst.size(); j++) {
List<String> list = lst.get(j);
row = sheet.createRow(j+1);
for (int k=0;k<list.size();k++) {
createMyCell(wb,row,k).setCellValue(list.get(k));
}
}
}
}