package com.cck.common.Utils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* @program: Iplan_NkaRka_server
* @description: DownExcel
* @author: LiuZhiFeng
* @create: 2021-07-30 10:31
**/
public class RowDataExcelUtil {
public static void writeRowExcel(List<LinkedHashMap> list,
HttpServletResponse response,
String channelType) throws IOException {
XSSFWorkbook xssfWorkbook = null;
xssfWorkbook = new XSSFWorkbook();
//创建工作表
XSSFSheet xssfSheet;
xssfSheet = xssfWorkbook.createSheet();
//创建行
XSSFRow xssfRow;
//创建列,即单元格Cell
XSSFCell xssfCell;
xssfRow = xssfSheet.createRow(0);
Map map = list.get(0);
Iterator iterator = map.entrySet().iterator();
int j=0;
while (iterator.hasNext()) {
Entry next = (Entry) iterator.next();
xssfCell = xssfRow.createCell(j);
xssfCell.setCellValue(next.getKey().toString());
j++;
}
int k =0;
for (int i = 0; i < list.size(); i++) {
Map map1 = list.get(i);
xssfRow = xssfSheet.createRow(i + 1);
for(Object obj:map1.values()){
System.out.println("value:"+obj);
xssfCell = xssfRow.createCell(k);
xssfCell.setCellValue(String.valueOf(obj));
k++;
}
k=0;
}
String headStr = "attachment; filename="" +channelType+ "-RowData.xlsx"";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", headStr);//
OutputStream outl = response.getOutputStream();
//FileOutputStream outl=new FileOutputStream("D://"+fileName);
//用输出流写到excel
try {
xssfWorkbook.write(outl);
outl.flush();
}catch (IOException e) {
e.printStackTrace();
}finally {
outl.close();
}
}
}