#yyds干货盘点#java导出excel文件

幼敏悟过人,读书辄成诵。这篇文章主要讲述#yyds干货盘点#java导出excel文件相关的知识,希望能为你提供帮助。
1.export函数

//导出文件接口
public String export()
return this.myExport(exportList);

2.导出列名
private String myExport(List< BusinessDept> list)
com.bronzesoft.power.tools.json.JSONObject info = new com.bronzesoft.power.tools.json.JSONObject();
try
List< String> headList = new ArrayList< String> (Arrays.asList("年", "月", "部门","部门负责人","经营值","收入", "支出","填报工时","标准工时","经营参数"));
Commonutil.export(list,headList,"部门经营总览导出");

info = Commonutil.setInfo(info,"部门经营总览导出");
catch (Exception e)
LogUtil.error(this.getClass().getName()+".exportExcel()", e);

return info.toString();

3.export实现方法
?首先,理解一下一个Excel的文件的组织形式,一个Excel文件对应于一个workbook(XSSFWorkbook),一个workbook可以有多个sheet(XSSFSheet)组成,一个sheet是由多个row(XSSFRow)组成,一个row是由多个cell(XSSFCell)组成。?
【#yyds干货盘点#java导出excel文件】
public static < T> boolean export(List< T> list,List< String> headList,String fileName)
return myExport(list,headList,fileName,com.bronzesoft.rdm.platform.util.Constants.PATH + com.bronzesoft.power.platform.Constants.TEMPFOLDER_DIR );

//将list导出为excel,文件名为fileName
public static < T> boolean myExport(List< T> list,List< String> headList,String fileName,String path)
try
if(!checkListAndHead(list,headList))
LogUtil.info("head的长度有问题,导出的文件不正确" );

File file = new File(path + File.separator + fileName + ".xlsx");
if(!file.exists())
file.createNewFile();

//创建对应excel文件,存储路径path待确定
XSSFWorkbook workBook = new XSSFWorkbook();
//创建一个excel的sheet页
XSSFSheet sheet = workBook.createSheet(fileName);
XSSFRow row = null;
XSSFCell cell = null;

Map< String, CellStyle> styles = StyleUtil.createStyles(workBook);

//表头样式
CellStyle headCenterIndex = styles.get("headCenter");
//列的样式居中,背景颜色为白色
CellStyle center = styles.get("centerWhite");
row = sheet.createRow(0);
//表头数据
for (int i = 0; i < headList.size(); i++)
//创建列
cell = row.createCell(i);
//设置列的value
cell.setCellValue(headList.get(i));
//设置列的样式
cell.setCellStyle(headCenterIndex);

//表格数据

//写入表格数据
String codeName = "";
int rownum = 1;
T obj = null;

for(int i = 0; i < list.size(); i++)
obj = list.get(i);
if(null != obj)
Field[] fields = obj.getClass().getDeclaredFields();
row = sheet.createRow(rownum);
for(int j = 0; j< fields.length; j++)
fields[j].setAccessible(true);
codeName = String.valueOf(fields[j].get(obj));
//创建第j列
cell = row.createCell(j);
cell.setCellValue(Commonutil.getStringVal(codeName));
cell.setCellStyle(center);


rownum++;

////i代表列,设置列的宽度
//for (int i = 0; i < headList.size(); i++)
//if(i == 0)
//sheet.setColumnWidth(i, 2000);
//else if(i == 1 || i == 3)
//sheet.setColumnWidth(i, 6000);
//else
//sheet.setColumnWidth(i, 4000);
//
//

//将文件写到临时目录

    推荐阅读