当前位置:网站首页>[npoi] C copy sheet template across workbooks to export Excel

[npoi] C copy sheet template across workbooks to export Excel

2022-06-26 17:33:00 Guistar~~

The article introduces

  • Only read xlsx Postfix file ,xls You need to add
  • Because my company has built a new computer environment excel It will be encrypted automatically , So I can only read an unencrypted one first excel Templates ( You need to apply to the leader , If it is changed, it will be automatically encrypted ), Create another excel, And write the template you read in the process

Reference resources

NPOI Copy template export Excel

Use

Read the template

        /// <summary>
        ///  Read the template 
        /// </summary>
        /// <param name="sheetname"> Pass in a table name </param>
        /// <returns></returns>
        public static XSSFWorkbook SheetCopytest(string sheetname)
        {
    
            //  Template address 
            string templetfilepath = @"C:\Users\10774114\Desktop\SHEET\Ulami Department daily report template .xlsx";// Template Excel
            //  Generate file address 
            string tpath = @"C:\Users\10774114\Desktop\SHEET\11.xlsx";// The mediation Excel, Use it as an intermediary to export , Avoid using modules directly Excel And change the format of the module 

            FileInfo ff = new FileInfo(tpath);
            if (ff.Exists)
            {
    
                ff.Delete();
            }

            //  Read the template 
            FileStream fileRead = new FileStream(templetfilepath, FileMode.Open, FileAccess.Read);
            XSSFWorkbook XSSFWorkbook = new XSSFWorkbook(fileRead);


            XSSFWorkbook book2 = new XSSFWorkbook();

            XSSFSheet CPS = (XSSFSheet)XSSFWorkbook.GetSheetAt(1); //  Get template sheet


            CPS.CopyTo(book2, sheetname, true, true); //  Put the template sheet Copy to the target workbook and name 

            return book2;
        }

Generate Excel

        public static string DataTableToExcel()
        {
    
            string sheetname = "20220601";
            XSSFWorkbook book2 = SheetCopytest(sheetname);
            using (FileStream file = new FileStream(@"C:\Users\10774114\Desktop\SHEET\11.xlsx", FileMode.Create, FileAccess.Write))
            {
    
                book2.Write(file);
                file.Close();
            }
            return sheetname;
        }
原网站

版权声明
本文为[Guistar~~]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206261718045592.html