生成PDF 并利用xls模板生成多个Sheet

using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;

using System.IO;    

 

 

    private void writeToExcel(HttpResponse res, int sheetCount, DataTable dateTable)
        {
            string orgfilepath = "D:\\iis folder\\web\\files\\templates\\STORAGE_RECEIVE\\HEARDRECEIVE_temp.xls";  //获得模版的路径     
            string tarfilepath = orgfilepath.Replace("HEARD", "TEMP" + DateTime.Now.ToString("mmddyyssffff"));   //要保存的新的文件名

            if (!File.Exists(orgfilepath))
            {
                return;
            }
            FileStream file = new FileStream(orgfilepath, FileMode.Open, FileAccess.Read);
            hssfworkbook = new HSSFWorkbook(file);


            Microsoft.Office.Interop.Excel.Application xApp = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook xBook;
            object oMiss = Missing.Value;

            System.IO.File.Copy(orgfilepath, tarfilepath, false);

            System.Globalization.CultureInfo currentCultureInfo = System.Globalization.CultureInfo.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            xBook = xApp.Workbooks.Open(tarfilepath, null, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss);
            Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)xBook.Worksheets[1];

            for (int j = 0; j < sheetCount - 1; j++)  //设置copy几个sheet
            {
                sheet.Copy(sheet, Type.Missing);
            }
            xBook.Save();

            xApp.Workbooks.Close();
            xApp.Quit();


            FileStream newfile = new FileStream(tarfilepath, FileMode.Open, FileAccess.Read);
            hssfworkbook = new HSSFWorkbook(newfile);

            for (int i = 0; i < myTable.Rows.Count; i++)
            {
                InputTOExcel();  //这个方法往模版里写内容

            }

            MemoryStream msfile = new MemoryStream();
            hssfworkbook.Write(msfile);
            System.IO.File.WriteAllBytes(tarfilepath, msfile.ToArray());


            string pdfFile = ComMethod.MadePDF(tarfilepath);

            byte[] datapdf = System.IO.File.ReadAllBytes(pdfFile);

            //删除模版
            //System.IO.DirectoryInfo di = new DirectoryInfo("D:\\iis folder\\web\\files\\templates\\STORAGE_RECEIVE");
            //FileInfo[] fis = di.GetFiles("TEMP*.*");
            //for (int i = 0; i < fis.Length; i++)
            //{

            //    File.Delete(fis[i].FullName);
            //}
            if (res != null)
            {
                res.ContentType = "application/octet-stream";
                res.AddHeader("Content-Disposition", "attachment;filename=" + "receive_" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");
                res.TransmitFile(pdfFile);
                //res.BinaryWrite(datapdf);
                res.End();
            }
        }

 

 

 

 /// <summary>
    /// 制作PDF文件
    /// </summary>
    /// <param name="TargetXlsFile">转换的xls文件</param>
    public static string MadePDF(string TargetXlsFile)
    {
        object oMiss = Missing.Value;

        Microsoft.Office.Interop.Excel.Application xApp = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel.XlFixedFormatType excelType = Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF;
        Microsoft.Office.Interop.Excel.Workbook xBookOK = xApp.Workbooks.Open(TargetXlsFile, null, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss);

        string pdfFile = TargetXlsFile.Replace(".xls", ".pdf");

        xBookOK.ExportAsFixedFormat(excelType, pdfFile, XlFixedFormatQuality.xlQualityStandard, true, false, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

        xApp.Workbooks.Close();
        xApp.Quit();

        return pdfFile;
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Java中根据模板导出Excel报表并复制模板生成多个Sheet页,可以使用Apache POI库。下面是一个简单的示例代码,可以将一个模板文件复制多次,并分别填充不同的数据,生成多个Sheet页: ```java import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ExcelExporter { public static void main(String[] args) throws IOException { // 加载模板文件 FileInputStream templateFile = new FileInputStream("template.xls"); Workbook templateWorkbook = new HSSFWorkbook(templateFile); // 获取模板中的样式和格式 Sheet templateSheet = templateWorkbook.getSheetAt(0); Row templateRow = templateSheet.getRow(0); Cell templateCell = templateRow.getCell(0); CellStyle templateStyle = templateCell.getCellStyle(); DataFormat templateFormat = templateWorkbook.createDataFormat(); // 模拟数据 List<Map<String, Object>> data = new ArrayList<>(); for (int i = 1; i <= 3; i++) { Map<String, Object> map = new HashMap<>(); map.put("name", "Tom" + i); map.put("age", 20 + i); data.add(map); } // 遍历数据,复制模板并填充数据 for (int i = 0; i < data.size(); i++) { Map<String, Object> map = data.get(i); // 复制模板 Sheet sheet = templateWorkbook.cloneSheet(0); templateWorkbook.setSheetName(templateWorkbook.getSheetIndex(sheet), "Sheet" + (i + 1)); // 填充数据 for (int j = 0; j < sheet.getLastRowNum() + 1; j++) { Row row = sheet.getRow(j); if (row == null) { row = sheet.createRow(j); } for (int k = 0; k < row.getLastCellNum(); k++) { Cell cell = row.getCell(k); if (cell == null) { cell = row.createCell(k); } String value = getValueForCell(cell, map); cell.setCellValue(value); cell.setCellStyle(templateStyle); if (value.matches("\\d+")) { // 如果是数字,设置单元格格式 cell.setCellStyle(getNumericCellStyle(templateWorkbook, templateStyle, templateFormat)); } } } } // 删除模板Sheet页 templateWorkbook.removeSheetAt(0); // 将工作簿保存到文件 FileOutputStream fileOut = new FileOutputStream("workbook.xls"); templateWorkbook.write(fileOut); fileOut.close(); System.out.println("Excel文件导出成功!"); } // 获取单元格的值 private static String getValueForCell(Cell cell, Map<String, Object> map) { String value = ""; if (cell.getCellType() == CellType.STRING) { value = cell.getStringCellValue(); if (value.startsWith("$")) { // 如果是占位符,替换为数据 value = map.get(value.substring(1)).toString(); } } return value; } // 获取数字类型单元格的样式 private static CellStyle getNumericCellStyle(Workbook workbook, CellStyle style, DataFormat format) { CellStyle newStyle = workbook.createCellStyle(); newStyle.cloneStyleFrom(style); newStyle.setDataFormat(format.getFormat("#,##0.00")); return newStyle; } } ``` 以上代码中,我们首先加载一个模板文件,并获取其中的样式和格式。接下来,我们模拟了一个数据集,然后遍历数据集,复制模板并填充数据,生成多个Sheet页。在填充数据时,我们首先遍历每个单元格,判断其是否为占位符,如果是,则替换为对应的数据。接着,我们将单元格的值设置为填充后的数据,并设置单元格的样式和格式。最后,我们删除了模板Sheet页,并将工作簿保存到文件中。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值