Java 新建excle文件并填充模版内容

Java 新建excle文件并填充模版内容

一、JAR

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.WorkbookFactory;
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 org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import com.xyzq.kettle.dao.KettleDao;
import com.xyzq.kettle.entity.KettleEntity;
import com.xyzq.pub.Pub;

二、主要功能实现代码

       //filename= P_gp_hs08.xlsx

        //判断文件是否存在,存在则追加,否则新增
        File file = new File(filepath+"/"+filename); 
        if (!file.exists() || !file.isFile()) {
            //logger.info("excle模板不存在,新增");
            XSSFWorkbook wb = new XSSFWorkbook();
            XSSFSheet sheetFlow = wb.createSheet("flow");
            XSSFRow rowFlow0 = sheetFlow.createRow(0);
            XSSFCell cellFlow0Flow = rowFlow0.createCell(0);
            cellFlow0Flow.setCellValue("flow名称");
            XSSFCell cellFlow0Remark = rowFlow0.createCell(1);
            cellFlow0Remark.setCellValue("备注");
            XSSFRow rowFlow1 = sheetFlow.createRow(1);
            XSSFCell cellFlow1Folw = rowFlow1.createCell(0);
            cellFlow1Folw.setCellValue("F_gp_"+list.get(0).getSysName());
            
            XSSFSheet sheetGroup = wb.createSheet("group");
            XSSFRow rowGroup0 = sheetGroup.createRow(0);
            XSSFCell cellGroup0Flow = rowGroup0.createCell(0);
            cellGroup0Flow.setCellValue("flow名称");
            XSSFCell cellGroup0Group = rowGroup0.createCell(1);
            cellGroup0Group.setCellValue("group名称");
            XSSFCell cellGroup0Remark = rowGroup0.createCell(2);
            cellGroup0Remark.setCellValue("备注");
            XSSFCell cellGroup0Relation = rowGroup0.createCell(2);
            cellGroup0Relation.setCellValue("依赖");
            
            XSSFSheet sheetJob = wb.createSheet("job");
            XSSFRow rowJob0 = sheetJob.createRow(0);
            XSSFCell cellJob0 = rowJob0.createCell(0);
            cellJob0.setCellValue("flow名称");
            XSSFCell cellJob1 = rowJob0.createCell(1);
            cellJob1.setCellValue("group名称");
            XSSFCell cellJob2 = rowJob0.createCell(2);
            cellJob2.setCellValue("job名称");
            XSSFCell cellJob3 = rowJob0.createCell(3);
            cellJob3.setCellValue("备注");
            XSSFCell cellJob4 = rowJob0.createCell(4);
            cellJob4.setCellValue("依赖");
            XSSFCell cellJob5 = rowJob0.createCell(5);
            cellJob5.setCellValue("类型");
            XSSFCell cellJob6 = rowJob0.createCell(6);
            cellJob6.setCellValue("命令");
            XSSFCell cellJob7 = rowJob0.createCell(7);
            cellJob7.setCellValue("参数变量");
            XSSFCell cellJob8 = rowJob0.createCell(8);
            cellJob8.setCellValue("重试次数");
            XSSFCell cellJob9 = rowJob0.createCell(9);
            cellJob9.setCellValue("重试间隔");
            XSSFCell cellJob10 = rowJob0.createCell(10);
            cellJob10.setCellValue("超时时间");
            
            FileOutputStream output;
            try {
                output = new FileOutputStream(filepath+"/"+filename);
                wb.write(output);
                output.flush();
                output.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                logger.info("excle模板创建异常:"+e.toString());
            }    
        }

 

转载于:https://www.cnblogs.com/lizm166/p/10650768.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
//region 数据源 List resultList = new ArrayList(); Model model = new Model(); model.setCode("01"); model.setName("测试1"); resultList.add(model); model = new Model(); model.setCode("02"); model.setName("测试2"); resultList.add(model); //endregion //获得模版 File directory = new File("src/main/resources/templates"); String templatePath = directory.getCanonicalPath(); String templateFile = templatePath + "\\template.xls"; //导出文件名 SimpleDateFormat simpl = new SimpleDateFormat("yyyyMMddHHmmss"); String currntTime = simpl.format(new Date()); String fileName = currntTime + "报表.xls"; //将结果放入 Map beans = new HashMap(); List values = new ArrayList(); values.add(resultList); beans.put("values", values); beans.put("title", "测试title"); //文件名称统一编码格式 fileName = URLEncoder.encode(fileName, "utf-8"); //生成的导出文件 File destFile = File.createTempFile(fileName, ".xls"); //transformer转到Excel XLSTransformer transformer = new XLSTransformer(); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { //将数据添加到模版中生成新的文件 transformer.transformXLS(templateFile, beans, destFile.getAbsolutePath()); //将文件输入 InputStream inputStream = new FileInputStream(destFile); //设置response参数,可以打开下载页面 response.reset(); //设置响应文本格式 response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1")); //将文件输出到页面 ServletOutputStream out = response.getOutputStream(); bis = new BufferedInputStream(inputStream); bos = new BufferedOutputStream(out)
好的,下面是一个简单的Java代码示例,用于填充Excel模板中的动态表格: ```java import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelTemplate { public static void main(String[] args) throws Exception { // 读取Excel模板 FileInputStream inputStream = new FileInputStream("template.xlsx"); Workbook workbook = new XSSFWorkbook(inputStream); Sheet sheet = workbook.getSheetAt(0); // 准备动态表格数据 List<Map<String, Object>> data = new ArrayList<>(); Map<String, Object> row1 = new HashMap<>(); row1.put("name", "Alice"); row1.put("age", 25); row1.put("gender", "Female"); data.add(row1); Map<String, Object> row2 = new HashMap<>(); row2.put("name", "Bob"); row2.put("age", 30); row2.put("gender", "Male"); data.add(row2); // 查找动态表格 int startRow = -1, endRow = -1, startCol = -1, endCol = -1; for (Row row : sheet) { for (Cell cell : row) { String cellText = cell.getStringCellValue().trim().toLowerCase(); if (cellText.equals("start")) { startRow = row.getRowNum(); startCol = cell.getColumnIndex(); } else if (cellText.equals("end")) { endRow = row.getRowNum(); endCol = cell.getColumnIndex(); } } } // 填充动态表格 if (startRow != -1 && endRow != -1 && startCol != -1 && endCol != -1) { int rowIndex = startRow + 1; for (Map<String, Object> rowData : data) { Row row = sheet.createRow(rowIndex++); for (int colIndex = startCol; colIndex <= endCol; colIndex++) { Cell cell = row.createCell(colIndex); String cellText = sheet.getRow(startRow).getCell(colIndex).getStringCellValue().trim().toLowerCase(); if (rowData.containsKey(cellText)) { Object value = rowData.get(cellText); if (value instanceof String) { cell.setCellValue((String) value); } else if (value instanceof Number) { cell.setCellValue(((Number) value).doubleValue()); } else if (value instanceof Boolean) { cell.setCellValue((Boolean) value); } } } } sheet.shiftRows(endRow + 1, sheet.getLastRowNum(), data.size() - 1); } // 保存Excel文件 FileOutputStream outputStream = new FileOutputStream("output.xlsx"); workbook.write(outputStream); workbook.close(); } } ``` 在这个示例中,我们假设模板文件中存在一个动态表格,其中包含在以单元格文本"start"和"end"之间的所有单元格。我们首先打开模板文件,然后准备动态表格的数据。数据是一个包含多个行的列表,每个行是一个包含一个或多个键值对的映射。键是表格中的列标题,值是该列的单元格值。接下来,我们在工作表中查找动态表格的起始和结束单元格,并将其行和列索引保存在变量中。然后,我们遍历数据列表并将每行数据复制到新的行中。我们为每行创建一个新行,并在动态表格的每个列中填充对应的值。最后,我们使用输出流将工作簿写入输出文件,并关闭工作簿。 请注意,此示例假定动态表格中的列标题与数据中的键相匹配,并且数据中的值可以转换为单元格值。如果您的模板文件具有不同的结构或数据类型,请相应地修改代码。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值