C#使用NPOI导出Excel文件

一、NPOI简介

NPOI 是 POI 项目的 .NET 版本。POI是一个开源的Java读写Excel、WORD等微软OLE2组件文档的项目。
 
使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写。NPOI是构建在POI 3.x版本之上的,它可以在没有安装Office的情况下对Word/Excel文档进行读写操作。

NPOI官方教程地址:http://tonyqus.sinaapp.com

googlecode:http://code.google.com/p/npoi/

codeplex:http://npoi.codeplex.com/

二、导出Excel帮助类

/***
*	Title:" " 项目
*		主题:用NPOI导出Excel文件
*	Description:
*		功能:XXX
*	Date:2019
*	Version:0.1版本
*	Author:Coffee
*	Modify Recoder:
*/

using System;
using System.Data;
using System.IO;
using System.Text;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

namespace kernal
{
    public class NPOIHelper
	{
        #region   文件属性信息
        static string companyName = "测试公司";                                     //公司名称
        static string subject = "主题名称";                                         //主题名称
        static string author = "测试作者";                                          //作者名称

        #endregion


        /// <summary>
        /// Excel文件设置与数据处理
        /// </summary>
        /// <param name="table">数据表</param>
        /// <param name="headerText">头部文本</param>
        /// <param name="sheetName">表的名称</param>
        /// <param name="columnName">数据列名称</param>
        /// <param name="columnTitle">表标题</param>
        /// <returns></returns>
        public static HSSFWorkbook ExcelSettingsAndHandleData(DataTable table, string headerText, string sheetName, string[] columnName, string[] columnTitle)
        {
            HSSFWorkbook hssfworkbook = new HSSFWorkbook();
            ISheet sheet = hssfworkbook.CreateSheet(sheetName);

            #region 设置文件属性信息

            //创建一个文档摘要信息实体。
            DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
            dsi.Company = companyName; //公司名称
            hssfworkbook.DocumentSummaryInformation = dsi;

            //创建一个摘要信息实体。
            SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
            si.Subject = subject;
            si.Author = author;
            si.Title = headerText;
            si.Subject = headerText;
            si.CreateDateTime = DateTime.Now;
            hssfworkbook.SummaryInformation = si;

            #endregion

            ICellStyle dateStyle = hssfworkbook.CreateCellStyle();
            IDataFormat format = hssfworkbook.CreateDataFormat();
            dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");

            #region 取得列宽

            int[] colWidth = new int[columnName.Length];
            for (int i = 0; i < columnName.Length; i++)
            {
                colWidth[i] = Encoding.GetEncoding(936).GetBytes(columnTitle[i]).Length;
            }
            for (int i = 0; i < table.Rows.Count; i++)
            {
                for (int j = 0; j < columnName.Length; j++)
                {
                    int intTemp = Encoding.GetEncoding(936).GetBytes(table.Rows[i][columnName[j]].ToString()).Length;
                    if (intTemp > colWidth[j])
                    {
                        colWidth[j] = intTemp;
                    }
                }
            }

            #endregion

            int rowIndex = 0;
            foreach (DataRow row in table.Rows)
            {
                #region 新建表,填充表头,填充列头,样式
                if (rowIndex == 65535 || rowIndex == 0)
                {
                    if (rowIndex != 0)
                    {
                        sheet = hssfworkbook.CreateSheet(sheetName + ((int)rowIndex / 65535).ToString());
                    }

                    #region 表头及样式
                    //if (!string.IsNullOrEmpty(headerText))
                    {
                        IRow headerRow = sheet.CreateRow(0);
                        headerRow.HeightInPoints = 25;
                        headerRow.CreateCell(0).SetCellValue(headerText);

                        ICellStyle headStyle = hssfworkbook.CreateCellStyle();
                        headStyle.Alignment = HorizontalAlignment.Center;
                        IFont font = hssfworkbook.CreateFont();
                        font.FontHeightInPoints = 20;
                        font.Boldweight = 700;
                        headStyle.SetFont(font);

                        headerRow.GetCell(0).CellStyle = headStyle;
                        sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, table.Columns.Count - 1));

                       
                    }
                    #endregion

                    #region 列头及样式
                    {
                        IRow headerRow;

                        headerRow = sheet.CreateRow(1);

                        ICellStyle headStyle = hssfworkbook.CreateCellStyle();
                        headStyle.Alignment = HorizontalAlignment.Center;
                        IFont font = hssfworkbook.CreateFont();
                        font.FontHeightInPoints = 10;
                        font.Boldweight = 700;
                        headStyle.SetFont(font);

                        for (int i = 0; i < columnName.Length; i++)
                        {
                            headerRow.CreateCell(i).SetCellValue(columnTitle[i]);
                            headerRow.GetCell(i).CellStyle = headStyle;
                            //设置列宽 
                            if ((colWidth[i] + 1) * 256 > 30000)
                            {
                                sheet.SetColumnWidth(i, 10000);
                            }
                            else
                            {
                                sheet.SetColumnWidth(i, (colWidth[i] + 1) * 256);
                            }
                        }
                       
                    }
                    #endregion

                    rowIndex = 2;


                }
                #endregion

                #region 填充数据

                IRow dataRow = sheet.CreateRow(rowIndex);
                for (int i = 0; i < columnName.Length; i++)
                {
                    ICell newCell = dataRow.CreateCell(i);

                    string drValue = row[columnName[i]].ToString();

                    switch (table.Columns[columnName[i]].DataType.ToString())
                    {
                        case "System.String"://字符串类型   
                            if (drValue.ToUpper() == "TRUE")
                                newCell.SetCellValue("是");
                            else if (drValue.ToUpper() == "FALSE")
                                newCell.SetCellValue("否");
                            newCell.SetCellValue(drValue);
                            break;
                        case "System.DateTime"://日期类型    
                            DateTime dateV;
                            DateTime.TryParse(drValue, out dateV);
                            newCell.SetCellValue(dateV);

                            newCell.CellStyle = dateStyle;//格式化显示    
                            break;
                        case "System.Boolean"://布尔型    
                            bool boolV = false;
                            bool.TryParse(drValue, out boolV);
                            if (boolV)
                                newCell.SetCellValue("是");
                            else
                                newCell.SetCellValue("否");
                            break;
                        case "System.Int16"://整型    
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            int intV = 0;
                            int.TryParse(drValue, out intV);
                            newCell.SetCellValue(intV);
                            break;
                        case "System.Decimal"://浮点型    
                        case "System.Double":
                            double doubV = 0;
                            double.TryParse(drValue, out doubV);
                            newCell.SetCellValue(doubV);
                            break;
                        case "System.DBNull"://空值处理    
                            newCell.SetCellValue("");
                            break;
                        default:
                            newCell.SetCellValue("");
                            break;
                    }

                }

                #endregion

                rowIndex++;
            }

            return hssfworkbook;
        }


        /// <summary>
        /// 将数据写入Excel文件
        /// </summary>
        /// <param name="hssfworkbook">工作簿</param>
        /// <param name="exportPath">文件导出路径</param>
        private static void WirteToFile(HSSFWorkbook hssfworkbook,string exportPath)
        {
            FileStream file = null;
            try
            {
                file = new FileStream(exportPath + ".xls", FileMode.Create);
                hssfworkbook.Write(file);
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                file.Dispose();
                hssfworkbook.Close();
            }

        }

        /// <summary>
        /// 导出Excel文件
        /// </summary>
        /// <param name="table">数据表</param>
        /// <param name="headerText">头部文本。</param>
        /// <param name="sheetName">工作表名称</param>
        /// <param name="columnName">数据列对应字段名称。</param>
        /// <param name="columnTitle">数据列对应字段的中文名称</param>
        /// <param name="fileName">文件名称</param>
        /// <param name="exportFilePath">导出的文件路径</param>
        public static void  ExportExcel(DataTable table, string headerText, string sheetName, string[] columnName, string[] columnTitle, string fileName,string exportFilePath)
        {
            //Excel文件设置与数据处理
            HSSFWorkbook hssfworkbook = ExcelSettingsAndHandleData(table, headerText, sheetName, columnName, columnTitle);
            //将数据写入Excel文件
            WirteToFile(hssfworkbook, exportFilePath+fileName);
        }

       

    }//Class_end
}

三、导出Excel帮助类的使用方法

/***
*	Title:" " 项目
*		主题:XXX
*	Description:
*		功能:XXX
*	Date:2019
*	Version:0.1版本
*	Author:Coffee
*	Modify Recoder:
*/

using Control;
using Global;
using kernal;
using NPOI.SS.Formula.Functions;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using UnityEngine;

namespace TestExport
{
	public class Test_ExportExcel : MonoBehaviour
	{
		void Start()
		{
			
		}

        private void Update()
        {
            if (Input.GetKeyDown(KeyCode.O))
            {
                //导出Excle文件
                ExportExcel();
            }
        }

        //导出Excle文件
        private void ExportExcel()
        {
            string path = @"C:\Users\CoffeeMilk\Desktop\新建文件夹\测试\";
            ExportData(path);
        }

        //人员信息
        private DataTable PeopleInfo()
        {
            DataTable dtAllPeopleInfoData = new DataTable();

            dtAllPeopleInfoData.Columns.Add("Number");                          //数据序号
            dtAllPeopleInfoData.Columns.Add("ID");                              //用户编号
            dtAllPeopleInfoData.Columns.Add("UserName");                        //用户名称
            dtAllPeopleInfoData.Columns.Add("TelNumber");                       //联系电话
            dtAllPeopleInfoData.Columns.Add("UserDealer");                      //公司名称
            dtAllPeopleInfoData.Columns.Add("DealerAddress");                   //公司地址
            dtAllPeopleInfoData.Columns.Add("RegisterTime");                    //注册时间

            DataRow row = null;
            int peopleTotalNumbers = 0;                                           //当前导出人员信息的总数
            List<Ctrl_PeopleInfoData> _PeopleInfoDatas = new List<Ctrl_PeopleInfoData>();//当前需要导出的人员信息集合
            peopleTotalNumbers = Ctrl_CommonPeopleInfoOperation.GetInstance().QueryPeopleInfoTotalNumbers();//人员总数
            _PeopleInfoDatas = Ctrl_CommonPeopleInfoOperation.GetInstance().QueryAllPeopleInfoOfIndexAndDisplyNumbers(0, peopleTotalNumbers);



            for (int i = 0; i < peopleTotalNumbers; i++)
            {
                row = dtAllPeopleInfoData.NewRow();
                row["Number"] = i + 1;
                row["ID"] = _PeopleInfoDatas[i].ID;
                row["UserName"] = _PeopleInfoDatas[i].UserName;
                row["TelNumber"] = _PeopleInfoDatas[i].TelNumber;
                row["UserDealer"] = _PeopleInfoDatas[i].UserDealer;
                row["DealerAddress"] = _PeopleInfoDatas[i].DealerAddress;
                row["RegisterTime"] = _PeopleInfoDatas[i].RegisterTime;
                dtAllPeopleInfoData.Rows.Add(row);
            }

            return dtAllPeopleInfoData;
           
            
        }

        

        //维修计划
        private DataTable RepairPlan()
        {
            DataTable dtAllInfoData = new DataTable();
            dtAllInfoData.Columns.Add("Number");                          //数据序号
            dtAllInfoData.Columns.Add("RepairPartName");                  //维修部件
            dtAllInfoData.Columns.Add("RepairTime");                      //维修时间
            dtAllInfoData.Columns.Add("RepairName");                      //维修人员
            dtAllInfoData.Columns.Add("IsRepair");                        //是否维修
            dtAllInfoData.Columns.Add("IsPass");                          //是否通过
            dtAllInfoData.Columns.Add("RepairContent");                   //维修内容

            //dtAllInfoData.Columns.Add("AuditorName");                     //审核人员

            DataRow row = null;
            int TotalNumbers = 0;                                                 //当前导出维修计划信息的总数
            List<Ctrl_View_RepairPlan_Data> _View_RepairPlan_Datas = new List<Ctrl_View_RepairPlan_Data>();//当前需要导出的维修计划信息集合

            TotalNumbers = Ctrl_CommonView_RepairPlanOperation.GetInstance().QueryRepairPlanTotalNumbers();//维修计划总数
            _View_RepairPlan_Datas = Ctrl_CommonView_RepairPlanOperation.GetInstance().QueryAllRepairPlanOfIndex(0, TotalNumbers);

            for (int i = 0; i < TotalNumbers; i++)
            {
                row = dtAllInfoData.NewRow();
                row["Number"] = i + 1;
                row["RepairPartName"] = _View_RepairPlan_Datas[i].RepairPartName;
                row["RepairTime"] = _View_RepairPlan_Datas[i].RepairTime;
                row["RepairName"] = _View_RepairPlan_Datas[i].RepairName;
                row["IsRepair"] = _View_RepairPlan_Datas[i].IsRepair;
                row["IsPass"] = _View_RepairPlan_Datas[i].IsPass;
                row["RepairContent"] = _View_RepairPlan_Datas[i].RepairContent;

                //row["AuditorName"] = _View_RepairPlan_Datas[i].AuditorName;
                dtAllInfoData.Rows.Add(row);
            }
            return dtAllInfoData;
        }

        private void ExportData(string filepath)
        {
             
             //DataTable table = PeopleInfo();
             DataTable table = RepairPlan();


            //string[] strFields = { "Number", "ID", "UserName", "TelNumber", "UserDealer", "DealerAddress", "RegisterTime"};
            //string[] strFieldsName = {"序号", "编号", "用户名称", "联系电话", "使用厂商", "使用商地址", "注册时间"};
            //NPOIHelper.Write(table, "人员信息表", "人员信息表", strFields, strFieldsName, "人员信息表", filepath);

            string[] strFields = { "Number", "RepairPartName", "RepairTime", "RepairName", "IsRepair", "IsPass", "RepairContent" };
            string[] strFieldsName = { "序号", "维修部件名称", "维修时间", "维修人员", "是否维修", "是否通过", "维修内容" };
            NPOIHelper.ExportExcel(table, "维修计划表", "维修维修计划表", strFields, strFieldsName, "维修计划表", filepath);

            Debug.Log("输出完成");
        }
    }
}

 四、导出效果图如下

 注意:本文内容参考:https://my.oschina.net/weisenz/blog/200653

NPOI导出Excel表功能实现(多个工作簿):http://www.cnblogs.com/zhengjuzhuan/archive/2010/02/01/1661103.html

在 Server 端存取 Excel 檔案的利器:NPOI Library:http://msdn.microsoft.com/zh-tw/ee818993.aspx

ASP.NET使用NPOI类库导出Excel:http://www.cnblogs.com/niunan/archive/2010/03/30/1700706.html

             
 

                                     

猜你喜欢

转载自blog.csdn.net/xiaochenXIHUA/article/details/89478266