poi实现数据导出成xlsx
作者:互联网
在工作中有遇到导出文件的功能要实现,直接贴代码
public void exportData(HttpServletResponse response) {
ServletOutputStream outputStream = null;
FileInputStream fileInputStream = null;
File temp = null;
JSONArray jsonArray=new JSONArray();//把数据放在jsonArray中
List<String> list=new ArrayList<>();
list.add("第一行");
list.add("第二行");
list.add("第三行");
list.stream().forEach(s -> {
JSONObject jsonObject=new JSONObject();
jsonObject.put("data",s);
jsonArray.add(jsonObject);
});
Map<String, String> headMap = new LinkedHashMap<>();// 存放表头部信息 必须是 LinkedHashMap
headMap.put("data","数据");//需要对应
// 生成文件临时存放目录
String tempFiles = System.getProperty("java.io.tmpdir") + "/";
String title = "信息数据明细.xlsx";
temp = new File(tempFiles, title);
if (!temp.getParentFile().exists()) {
temp.getParentFile().mkdirs();
}
try {
OutputStream outXlsx = new FileOutputStream(tempFiles + title);
exportToExcel(headMap, jsonArray, null, 0, outXlsx);
outXlsx.close();
//设置请求头
response.setHeader("content-type", "text/plain");
response.setHeader("content-type", "application/x-msdownload;");
response.setContentType("text/plain; charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename="
+ new String((title).getBytes(), StandardCharsets.ISO_8859_1));
outputStream = response.getOutputStream();
fileInputStream = new FileInputStream(tempFiles + title);
byte[] bytes = new byte[1024];
int size;
while (-1 != (size = fileInputStream.read(bytes))) {
outputStream.write(bytes, 0, size);
}
outputStream.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void exportToExcel(Map<String, String> headMap, JSONArray jsonArray, String datePattern, int colWidth, OutputStream out) {
if(datePattern==null) datePattern = "yyyy-MM-dd HH:mm:ss";
// 声明一个工作薄
SXSSFWorkbook workbook = new SXSSFWorkbook(1000);//缓存
//设置单元格风格,居中对齐. 垂直对齐
CellStyle cs = workbook.createCellStyle();
cs.setAlignment(HorizontalAlignment.CENTER_SELECTION);
cs.setVerticalAlignment(VerticalAlignment.DISTRIBUTED);
// 生成一个表格
SXSSFSheet sheet = workbook.createSheet();
//设置列宽
int minBytes = colWidth<50?50:colWidth;//至少字节数
int[] arrColWidth = new int[headMap.size()];
// 产生表格标题行,以及设置列宽
String[] properties = new String[headMap.size()];
String[] headers = new String[headMap.size()];
int ii = 0;
for (Iterator<String> iter = headMap.keySet().iterator(); iter
.hasNext();) {
String fieldName = iter.next();
properties[ii] = fieldName;
headers[ii] = headMap.get(fieldName);
int bytes = fieldName.getBytes().length;
arrColWidth[ii] = bytes < minBytes ? minBytes : bytes;
sheet.setColumnWidth(ii,arrColWidth[ii]*1024);
ii++;
}
// 遍历集合数据,产生数据行
int rowIndex = 0;
for (Object obj : jsonArray) {
if(rowIndex == 65535 || rowIndex == 0){
if ( rowIndex != 0 ) sheet = workbook.createSheet();//如果数据超过了,则在第二页显示
SXSSFRow headerRow = sheet.createRow(0); //列头 rowIndex =1
for(int i=0;i<headers.length;i++)
{ SXSSFCell newCell = headerRow.createCell(i);
newCell.setCellValue(headers[i]);
newCell.setCellStyle(cs);
}
rowIndex = 1;//数据内容从 rowIndex=1开始
}
JSONObject jo = (JSONObject) JSONObject.toJSON(obj);
SXSSFRow dataRow = sheet.createRow(rowIndex);
for (int i = 0; i < properties.length; i++)
{
SXSSFCell newCell = dataRow.createCell(i);
Object o = jo.get(properties[i]);
String cellValue = "";
if(o==null) cellValue = "";
else if(o instanceof Date) cellValue = new SimpleDateFormat(datePattern).format(o);
else if(o instanceof Float || o instanceof Double)
cellValue= new BigDecimal(o.toString()).setScale(2,BigDecimal.ROUND_HALF_UP).toString();
else cellValue = o.toString();
newCell.setCellValue(cellValue);
newCell.setCellStyle(cs);
}
rowIndex++;
}
// 自动调整宽度 并且调整默认单元格长度为6个中文字符
sheet.trackAllColumnsForAutoSizing();
for (int i =0; i < headers.length; i++) {
sheet.autoSizeColumn(i);
int width = Math.max(15 * 256, Math.min(255 * 256, sheet.getColumnWidth(i) * 12 / 10));
sheet.setColumnWidth(i, width);
}
try {
workbook.write(out);//将工作簿写入outPutStream
workbook.close();
boolean flag = workbook.dispose();//释放磁盘空间。处理在磁盘上支持这个工作簿的临时文件。调用该方法将使工作簿不可用。
System.out.println(flag);//如果所有临时文件都被成功删除,则为真。
} catch (IOException e) {
e.printStackTrace();
}
}
标签:xlsx,headMap,sheet,String,int,导出,rowIndex,poi,new 来源: https://blog.csdn.net/gfdedexdcf/article/details/117033895