1. 程式人生 > 其它 >C# NPOI匯入/匯出Excel

C# NPOI匯入/匯出Excel

安裝

Install-Package NPOI

ExcelHelper

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Data;
using System.IO;

namespace ConsoleApp1
{
    public class ExcelHelper
    {
        /// <summary>
        /// 根據Excel檔案型別返回IWorkbook
        /// </summary>
        /// <param name="fileName">檔案路徑</param>
        /// <returns></returns>
        private IWorkbook GetWorkbook(string fileName)
        {
            if (File.Exists(fileName))
            {
                using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    if (Path.GetExtension(fileName).Equals(".xlsx")) return new XSSFWorkbook(fs);
                    else return new HSSFWorkbook(fs);
                }
            }
            else
            {
                if (Path.GetExtension(fileName).Equals(".xlsx")) return new XSSFWorkbook();
                else return new HSSFWorkbook();
            }
        }

        /// <summary>
        /// 將excel中的資料匯入到DataTable中
        /// </summary>
        /// <param name="fileName">excel檔案路徑</param>
        /// <param name="sheetName">excel工作薄sheet的名稱</param>
        /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
        /// <returns>返回的DataTable</returns>
        public DataTable ExcelToDataTable(string fileName, bool isFirstRowColumn = true, string sheetName = null)
        {
            DataTable data = new DataTable();
            IWorkbook workbook = GetWorkbook(fileName);
            ISheet sheet;
            if (sheetName != null)
            {
                sheet = workbook.GetSheet(sheetName);
                if (sheet == null) //如果沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet
                {
                    sheet = workbook.GetSheetAt(0);
                }
            }
            else
            {
                sheet = workbook.GetSheetAt(0);
            }
            if (sheet != null)
            {
                IRow firstRow = sheet.GetRow(0);
                if (firstRow != null)
                {
                    int cellCount = firstRow.LastCellNum; //一行最後一個cell的編號 即總的列數

                    int startRow;
                    if (isFirstRowColumn)
                    {
                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                        {
                            ICell cell = firstRow.GetCell(i);
                            if (cell != null)
                            {
                                string cellValue = cell.StringCellValue;
                                if (cellValue != null)
                                {
                                    DataColumn column = new DataColumn(cellValue);
                                    data.Columns.Add(column);
                                }
                            }
                        }
                        startRow = sheet.FirstRowNum + 1;
                    }
                    else
                    {
                        for (int i = firstRow.FirstCellNum; i < cellCount; i++)
                        {
                            DataColumn column = new DataColumn(i.ToString());
                            data.Columns.Add(column);
                        }
                        startRow = sheet.FirstRowNum;
                    }

                    //最後一列的標號
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //沒有資料的行預設是null       

                        DataRow dataRow = data.NewRow();
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            if (row.GetCell(j) != null) //同理,沒有資料的單元格都預設是null
                                dataRow[j] = row.GetCell(j).ToString();
                        }
                        data.Rows.Add(dataRow);
                    }
                }
            }
            return data;
        }

        /// <summary>
        /// 將DataTable中的資料匯入到excel中
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="path">檔案路徑</param>
        public void DataTableToExcel(DataTable dt, string path)
        {
            IWorkbook workbook = GetWorkbook(path);
            ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);//建立工作表
            #region 標題
            IRow row = sheet.CreateRow(0);//在工作表中新增一行
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ICell cell = row.CreateCell(i);//在行中新增一列
                cell.SetCellValue(dt.Columns[i].ColumnName);//設定列的內容	 
            }
            #endregion
            #region 填充資料
            for (int i = 1; i <= dt.Rows.Count; i++)//遍歷DataTable行
            {
                DataRow dataRow = dt.Rows[i - 1];
                row = sheet.CreateRow(i);//在工作表中新增一行

                for (int j = 0; j < dt.Columns.Count; j++)//遍歷DataTable列
                {
                    ICell cell = row.CreateCell(j);//在行中新增一列
                    cell.SetCellValue(dataRow[j].ToString());//設定列的內容	 
                }
            }
            #endregion
            #region 輸出Excel
            MemoryStream ms = new MemoryStream();
            workbook.Write(ms);
            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                byte[] bArr = ms.ToArray();
                fs.Write(bArr, 0, bArr.Length);
                fs.Flush();
            }
            #endregion
        }

        /// <summary>
        /// 將excel中的資料匯入到DataSet中
        /// </summary>
        /// <param name="fileName">excel檔案路徑</param>
        /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
        /// <returns>返回的DataTable</returns>
        public DataSet ExcelToDataSet(string fileName, bool isFirstRowColumn = true)
        {
            DataSet ds = new DataSet();
            IWorkbook workbook = GetWorkbook(fileName);
            for (int e = 0; e < workbook.NumberOfSheets; e++)
            {
                DataTable data = new DataTable();
                ISheet sheet = workbook.GetSheetAt(e);
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(0);
                    if (firstRow != null)
                    {
                        int cellCount = firstRow.LastCellNum; //一行最後一個cell的編號 即總的列數

                        int startRow;
                        if (isFirstRowColumn)
                        {
                            for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                            {
                                ICell cell = firstRow.GetCell(i);
                                if (cell != null)
                                {
                                    string cellValue = cell.StringCellValue;
                                    if (cellValue != null)
                                    {
                                        DataColumn column = new DataColumn(cellValue);
                                        data.Columns.Add(column);
                                    }
                                }
                            }
                            startRow = sheet.FirstRowNum + 1;
                        }
                        else
                        {
                            for (int i = firstRow.FirstCellNum; i < cellCount; i++)
                            {
                                DataColumn column = new DataColumn(i.ToString());
                                data.Columns.Add(column);
                            }
                            startRow = sheet.FirstRowNum;
                        }

                        //最後一列的標號
                        int rowCount = sheet.LastRowNum;
                        for (int i = startRow; i <= rowCount; ++i)
                        {
                            IRow row = sheet.GetRow(i);
                            if (row == null) continue; //沒有資料的行預設是null       

                            DataRow dataRow = data.NewRow();
                            for (int j = row.FirstCellNum; j < cellCount; ++j)
                            {
                                if (row.GetCell(j) != null) //同理,沒有資料的單元格都預設是null
                                    dataRow[j] = row.GetCell(j).ToString();
                            }
                            data.Rows.Add(dataRow);
                        }
                        ds.Tables.Add(data);
                    }
                }
            }
            return ds;
        }

        /// <summary>
        /// 將DataSet中的資料匯入到excel中
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="path">檔案路徑</param>
        public void DataSetToExcel(DataSet ds, string path)
        {
            IWorkbook workbook = GetWorkbook(path);
            for (int d = 0; d < ds.Tables.Count; d++)
            {
                DataTable dt = ds.Tables[d];
                ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet" + d) : workbook.CreateSheet(dt.TableName);//建立工作表
                #region 標題
                IRow row = sheet.CreateRow(0);//在工作表中新增一行
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    ICell cell = row.CreateCell(i);//在行中新增一列
                    cell.SetCellValue(dt.Columns[i].ColumnName);//設定列的內容	 
                }
                #endregion
                #region 填充資料
                for (int i = 1; i <= dt.Rows.Count; i++)//遍歷DataTable行
                {
                    DataRow dataRow = dt.Rows[i - 1];
                    row = sheet.CreateRow(i);//在工作表中新增一行

                    for (int j = 0; j < dt.Columns.Count; j++)//遍歷DataTable列
                    {
                        ICell cell = row.CreateCell(j);//在行中新增一列
                        cell.SetCellValue(dataRow[j].ToString());//設定列的內容	 
                    }
                }
            }
            #endregion
            #region 輸出Excel
            MemoryStream ms = new MemoryStream();
            workbook.Write(ms);
            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                byte[] bArr = ms.ToArray();
                fs.Write(bArr, 0, bArr.Length);
                fs.Flush();
            }
            #endregion
        }
    }
}

呼叫

                    DataSet ds = new DataSet();
                    DataTable md = new DataTable("table1");
                    DataTable mdtb = new DataTable("table2");
                    md.Columns.Add("ID", Type.GetType("System.String"));
                    md.Columns.Add("Name", Type.GetType("System.String"));
                    mdtb.Columns.Add("TableName", Type.GetType("System.String"));
                    mdtb.Columns.Add("ProductName", Type.GetType("System.String"));
                    DataRow newRow, mdtbRow;
                    newRow = md.NewRow();
                    newRow["ID"] = Guid.NewGuid().ToString();
                    newRow["Name"] = Guid.NewGuid().ToString();
                    md.Rows.Add(newRow);
                    mdtbRow = mdtb.NewRow();
                    mdtbRow["TableName"] = Guid.NewGuid().ToString();
                    mdtbRow["ProductName"] = Guid.NewGuid().ToString();
                    mdtb.Rows.Add(mdtbRow);
                    ds.Tables.Add(md);
                    ds.Tables.Add(mdtb);

                    var excelPath = Path.Combine(Environment.CurrentDirectory, $"{Guid.NewGuid()}.xlsx");
                    new ExcelHelper().DataSetToExcel(ds, excelPath);