Excel导出java实例(有模板)

前台参照之前js数组转换成json数组的博文

后台:

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;


import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
* 导出日报的Excel文件
*/
public String exportRptDailyExcel(TProjProject currProj,String writeStartDate,String writeEndDate, List<RptDailyData> exportDataList) {

String result = "";

// 打开Excel模板
excelRptDailyTemplateAbsolutePath = calFileAbsoPathInTomcat(excelRptDailyTemplateRelativePath);
FileInputStream is = null;

try {
is = new FileInputStream(excelRptDailyTemplateAbsolutePath);
} catch (FileNotFoundException e2) {
e2.printStackTrace();
}

HSSFWorkbook wbs = null;

try {
wbs = new HSSFWorkbook(is);
} catch (IOException e1) {
e1.printStackTrace();
}

// 读取测点数据Sheet
HSSFSheet rptDailyDataSheet = wbs.getSheetAt(0);
System.out.println("行数: " + (rptDailyDataSheet.getLastRowNum() + 1));

// 写入表格title,表格title不用写,模板里面有
// HSSFRow gridTitleRow = pointDataSheet.createRow(2);
// HSSFCell gridTitleCell = gridTitleRow.createCell(0);
//        gridTitleCell.setCellValue("测点名称");
//        
//        gridTitleCell = gridTitleRow.createCell(1);
//        gridTitleCell.setCellValue("监测时间");
//        
//        gridTitleCell = gridTitleRow.createCell(2);
//        gridTitleCell.setCellValue("期次");
//        
//        gridTitleCell = gridTitleRow.createCell(3);
//        gridTitleCell.setCellValue("初始测值");
//        
//        gridTitleCell = gridTitleRow.createCell(4);
//        gridTitleCell.setCellValue("本次测值");
//        
//        gridTitleCell = gridTitleRow.createCell(5);
//        gridTitleCell.setCellValue("上次测值");
//
//        gridTitleCell = gridTitleRow.createCell(6);
//        gridTitleCell.setCellValue("单次变化");
//
//        gridTitleCell = gridTitleRow.createCell(7);
//        gridTitleCell.setCellValue("累计变化");
//
//        gridTitleCell = gridTitleRow.createCell(8);
//        gridTitleCell.setCellValue("变化速率");


        
        // 填充数据
        HSSFRow dataRow;


        for (int i = 0; i < exportDataList.size(); i++) {
       
        dataRow = rptDailyDataSheet.createRow(i + 3);   // 注意! 这里要加2,是因为表格中前面已经占据了三行,分别提示信息、显示总标题和表格标题
        RptDailyData rptDaily = exportDataList.get(i);


        System.out.print(rptDaily.getChangeRate());
            // 创建单元格,并设置值
        if(rptDaily.getWriteDate()==null){
        dataRow.createCell(0).setCellValue("/");
        }else{
        dataRow.createCell(0).setCellValue(rptDaily.getWriteDate());
        }
        if(rptDaily.getpStatusReport()==null){
        dataRow.createCell(1).setCellValue("/");
        }else{
        dataRow.createCell(1).setCellValue(rptDaily.getpStatusReport());
        }
        if(rptDaily.getPName()==null){
        dataRow.createCell(2).setCellValue("/");
        }else{
        dataRow.createCell(2).setCellValue(rptDaily.getPName());
        }
            if(rptDaily.getMonitorDate()==null){
            dataRow.createCell(3).setCellValue("/");
            }else{
            dataRow.createCell(3).setCellValue(rptDaily.getMonitorDate());
            }
            if(rptDaily.getWeather()==null){
            dataRow.createCell(4).setCellValue("/");
            }else{
            dataRow.createCell(4).setCellValue(rptDaily.getWeather());
            }
            if(rptDaily.getWritePerson()==null){
            dataRow.createCell(5).setCellValue("/");
            }else{
            dataRow.createCell(5).setCellValue(rptDaily.getWritePerson());
            }
            if(rptDaily.getMmName()==null){
            dataRow.createCell(6).setCellValue("/");
            }else{
            dataRow.createCell(6).setCellValue(rptDaily.getMmName());
            }
            dataRow.createCell(7).setCellValue(rptDaily.getIssue());
            if(rptDaily.getPointName()==null){
            dataRow.createCell(8).setCellValue("/");
            }else{
            dataRow.createCell(8).setCellValue(rptDaily.getPointName());
            }
            if(rptDaily.getThisvalue()==null){
            dataRow.createCell(9).setCellValue("/");
            }else{
            dataRow.createCell(9).setCellValue(rptDaily.getThisvalue());
            }
            if(rptDaily.getChangeThis()==null){
            dataRow.createCell(10).setCellValue("/");
            }else{
            dataRow.createCell(10).setCellValue(rptDaily.getChangeThis());
            }
            if(rptDaily.getChangeTotal()==null){
            dataRow.createCell(11).setCellValue("/");
            }else{
            dataRow.createCell(11).setCellValue(rptDaily.getChangeTotal());
            }
            if(rptDaily.getChangeRate()==null){
            dataRow.createCell(12).setCellValue("/");
            }else{
            dataRow.createCell(12).setCellValue(rptDaily.getChangeRate());
            }
            
            
        }

        // 将文件存到指定位置  
        try {
        String dirPath = "ReportExcelFile/";
        String folderDir = getFolderPath(dirPath);
       
        String projNamePart = "";
        String projMethodPart = "";
       
        if (currProj.getPName().length() >= 5) {
        projNamePart = currProj.getPName().substring(0, 5);
        } else {
        projNamePart = currProj.getPName();
        }
       
        // 计算最终的文件名
        String fileName = converterToSpell(projNamePart) + "_RptDaily"+writeStartDate+"_"+writeEndDate+".xls";
       
        // 创建文件夹
    File folder = new File(folderDir);
    if (!folder.exists() && !folder.isDirectory()) {
    System.out.println("目录不存在,准备创建该目录");
    folder.mkdirs();
    }


    String exportRptDailyFilePath = "";
    exportRptDailyFilePath = folderDir + fileName;
   
    System.out.println("文件夹目录:" + folderDir);
    System.out.println("exportPjmiFilePath = " + exportRptDailyFilePath);
   
        FileOutputStream fout = new FileOutputStream(exportRptDailyFilePath);
        wbs.write(fout);
        fout.close();
        result = dirPath + fileName;
        } catch (Exception e) { 
        e.printStackTrace();
        }


return result;
}

/**
* 汉字转换位汉语拼音,英文字符不变;导出的文件名中的工程名用拼音
* @param chines 汉字
* @return 拼音
*/
private String converterToSpell(String chines) {
String pinyinName = "";
char[] nameChar = chines.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < nameChar.length; i++) {
if (nameChar[i] > 128) {
try {
pinyinName += PinyinHelper.toHanyuPinyinStringArray(
nameChar[i], defaultFormat)[0] + '_';
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
pinyinName += nameChar[i];
}
}
return pinyinName.substring(0, pinyinName.length() - 1);
}

/*
* 按日报填写日期,顺序冒泡排序

* */
public void SortByWriteDate(List<RptDailyData> exportDataList) {
// TODO Auto-generated method stub
RptDailyData temp = null;
       boolean exchange = false;
       for (int i = 0; i < exportDataList.size(); i++) {
           exchange = false;
           for (int j = exportDataList.size() - 2; j >= i; j--) {
               if (exportDataList.get(j + 1).getWriteDate().compareTo(
                       exportDataList.get(j).getWriteDate()) < 0) {
                   temp = exportDataList.get(j + 1);
                   exportDataList.set(j + 1, exportDataList.get(j));
                   exportDataList.set(j, temp);
                   exchange = true;
               }
           }
           if (!exchange)
               break;
       }
       return;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这里是一个基于 EasyPoi 的 Excel 模板导出 Java 实例。 首先,你需要在你的项目中添加 EasyPoi 的依赖。如果你使用 Maven,可以在 `pom.xml` 文件中添加以下代码: ```xml <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>5.1.1</version> </dependency> ``` 然后,你需要准备好 Excel 模板文件,这个文件中可以包含一些占位符,例如 `{{name}}`。 接下来,你需要创建一个 Java 类,用于解析模板文件并填充数据。这个类可以继承 `AbstractExcelView` 类,并实现 `buildExcelDocument()` 方法。以下是一个简单的例子: ```java public class MyExcelView extends AbstractExcelView { @Override protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception { // 获取数据 List<MyData> dataList = (List<MyData>) model.get("dataList"); // 加载模板文件 InputStream inputStream = getClass().getResourceAsStream("/templates/my_template.xlsx"); ExcelTemplate template = ExcelTemplate.getInstance(inputStream); // 填充数据 template.putVar("title", "My Excel Report"); template.putVar("dataList", dataList); // 输出 Excel 文件 response.setContentType("application/vnd.ms-excel"); String fileName = "my_excel.xlsx"; response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); OutputStream outputStream = response.getOutputStream(); template.write(outputStream); outputStream.flush(); outputStream.close(); } } ``` 在这个例子中,我们假设模板文件名为 `my_template.xlsx`,并且包含两个占位符:`{{title}}` 和 `{{dataList}}`。 最后,你需要在你的控制器中调用这个视图,例如: ```java @GetMapping("/download") public ModelAndView download() { List<MyData> dataList = ...; // 获取数据 ModelAndView mav = new ModelAndView(new MyExcelView()); mav.addObject("dataList", dataList); return mav; } ``` 现在,当你访问 `/download` 路径时,就会下载一个填充好数据的 Excel 文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值