A Simple Implementation of Using NPOI to Export Excel Files in .Net

1. Install the corresponding NuGet package

 2. Write the corresponding NPOIHelper.cs

Here the table header is a string array passed in the business code, or it can be directly replaced by the columnName of the dataset

The order of creation is book -> sheet -> row; at the same time, simple style definition is also possible

using Microsoft.AspNetCore.Hosting;
using NPOI.SS.UserModel;
using System;
using System.Data;
using System.IO;

namespace ErpBarCodeService.Utils
{
    public class NpoiHelper
    {
        private static IHostingEnvironment _environment;
        public NpoiHelper(IHostingEnvironment iEnvironment)
        {
            _environment = iEnvironment;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dt">数据表</param>
        /// <param name="title">文件名称</param>
        /// <param name="headerarr">表头</param>
        /// <param name="resultMsg">错误信息</param>
        /// <param name="excelFilePath">文件路径</param>
        /// <returns></returns>
        public static bool NpoiExcel(DataTable dt,string title, string[] headerarr, out string resultMsg, out string excelFilePath)
        {
            bool result = true;
            excelFilePath = "";
            resultMsg = "";
            try
            {
                NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
                NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("Sheet1");
                NPOI.SS.UserModel.IRow headerrow = sheet.CreateRow(0);
                ICellStyle style = book.CreateCellStyle();
                style.Alignment = HorizontalAlignment.Center;
                style.VerticalAlignment = VerticalAlignment.Center;

                for (int i = 0; i < headerarr.Length; i++)
                {
                    ICell headercell = headerrow.CreateCell(i);
                    headercell.CellStyle = style;
                    headercell.SetCellValue(headerarr[i]);
                }
                // i 为行 j 为列
                for (int i = 1; i < dt.Rows.Count + 1; i++)
                {
                    IRow temprow = sheet.CreateRow(i);
                    for (int j = 0; j < headerarr.Length; j++)
                    {
                        ICell cell = temprow.CreateCell(j);
                        cell.CellStyle = style;
                        cell.SetCellValue(dt.Rows[i-1][j].ToString());
                    }
                }
                //保存文件 应用程序目录
                string rootPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                var uploadPath = rootPath + "/";
                string excelFileName = title + ".xls";
                string excelPath = uploadPath + excelFileName;

                var fileStream = new FileStream(excelPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                book.Write(fileStream);
                fileStream.Close();   // 关闭文件流
                fileStream.Dispose(); // 释放流所占用的资源

                //excel文件保存的相对路径,提供给前端下载
                var relativePositioning = "/" + excelFileName;
                excelFilePath = relativePositioning;
            }
            catch (Exception e)
            {
                result = false;
                resultMsg = e.Message;
            }
            return result;

        }

    }

}

3. Just call it in the code

bool export = NpoiHelper.NpoiExcel(ds.Tables[0], filename, headerarr, out resultMsg, out excelFilePath);
if (export)
{
    return new { code = 0, msg = excelFilePath };
}
else
{
    return new { code = -1, msg = resultMsg };
}
                

Guess you like

Origin blog.csdn.net/qq_41809961/article/details/129244297