Poi是不错的java操作excel的包,开发过程中遇到生成excel文件名乱码、sheet表名乱码的问题,在这里我给大家一个完整的解决方案。
首先我们要写一个生成excel的模板。新建如下servlet:
importjava.io.OutputStream;
importjava.util.List;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.poi.hssf.usermodel.HSSFCell;
importorg.apache.poi.hssf.usermodel.HSSFCellStyle;
importorg.apache.poi.hssf.usermodel.HSSFFont;
importorg.apache.poi.hssf.usermodel.HSSFRow;
importorg.apache.poi.hssf.usermodel.HSSFSheet;
importorg.apache.poi.hssf.usermodel.HSSFWorkbook;
publicclassExcelAction
{
publicstaticvoidexcel(HttpServletResponse
response, List list,
String[] firstLine, String sheetName, String fileName) {
String[] array1 =null;
try{
shorti
= 0;// row行标
response.setContentType("application/vnd.ms-excel");//设置生成的文件类型
response.setHeader("Content-Disposition", "filename="
+newString(fileName.getBytes("gb2312"),
"iso8859-1"));//设置文件头编码方式和文件名
HSSFWorkbook wb =newHSSFWorkbook();//excel文件,一个excel文件包含多个表
HSSFSheet sheet = wb.createSheet();//表,一个表包含多个行
wb.setSheetName(0, sheetName, HSSFWorkbook.ENCODING_UTF_16);//
设置sheet中文编码;
//设置字体等样式
HSSFFont font = wb.createFont();
font.setFontHeightInPoints((short)
12);
font.setFontName("Courier New");
HSSFCellStyle style = wb.createCellStyle();
style.setFont(font);
style.setWrapText(true);
style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
HSSFRow row;//行,一行包括多个单元格
HSSFCell cell;//单元格
row = sheet.createRow(i);//由HSSFSheet生成行
row.setHeightInPoints((float)
30);
//生成首行
for(shortj
= 0; j < firstLine.length; j++) {
cell = row.createCell(j);//由行生成单元格
cell.setCellStyle(style);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//
设置cell中文编码;
cell.setCellValue(firstLine[j]);
sheet.setColumnWidth(j, (short)
(5000));
}
//生成所有行的单元格内容,如果测试list设为null即可,或者将这一段代码注释掉
if(null==
list || list.size() == 0) {
// do nothing
}else{
for(intk
= 0; k < list.size(); k++) {
row = sheet.createRow(++i);
row.setHeightInPoints((float)
33);
array1 = (String[]) list.get(k);
if(null!=
array1 && array1.length != 0) {
for(intf
= 0; f < array1.length; f++) {
cell = row.createCell((short)
f);
cell.setCellStyle(style);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(array1[f]);
}
}
}
}
//输出
OutputStream out = response.getOutputStream();
wb.write(out);
out.close();
}catch(Exception
ex) {
ex.printStackTrace();
}
return;
}
}
如果觉得《java导出excel文件名乱码_Poi生成excel文件名乱码问题的解决方案》对你有帮助,请点赞、收藏,并留下你的观点哦!