C#使用NPOI讀寫excel(轉載)

轉載來源:https://www.cnblogs.com/masonmei/p/11526979.html

帖內容來自網絡+自己稍作整理,已找不到原貼,侵刪

個人比較習慣用NPOI操作excel,方便易理解。在宇宙第一IDE(笑)——VS2017中插入NPOI就很方便:

首先安裝NPOI:

 

然後在.cs文件中加入如下引用:

using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;

XSSF是用於.xlsx(2007以後版本)

HSSF是用於.xls(2007以前版本)

同時我的代碼中要用到Datatable,用於存儲表格數據

讀寫文件需要IO

using System.Data;
using System.IO

 

接下來是讀寫excel的代碼:

首先從excel中讀入數據存入datatable並返回:

複製代碼
        /// <summary>
        /// Excel導入成DataTble
        /// </summary>
        /// <param name="file">導入路徑(包含文件名與擴展名)</param>
        /// <returns></returns>
        public static DataTable ExcelToTable(string file)
        {
            DataTable dt = new DataTable();
            IWorkbook workbook;
            string fileExt = Path.GetExtension(file).ToLower();
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; }
                if (workbook == null) { return null; }
                ISheet sheet = workbook.GetSheetAt(0);

                //表頭  
                IRow header = sheet.GetRow(sheet.FirstRowNum);
                List<int> columns = new List<int>();
                for (int i = 0; i < header.LastCellNum; i++)
                {
                    object obj = GetValueType(header.GetCell(i));
                    if (obj == null || obj.ToString() == string.Empty)
                    {
                        dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                    }
                    else
                        dt.Columns.Add(new DataColumn(obj.ToString()));
                    columns.Add(i);
                }
                //數據  
                for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                {
                    DataRow dr = dt.NewRow();
                    bool hasValue = false;
                    foreach (int j in columns)
                    {
                        dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                        if (dr[j] != null && dr[j].ToString() != string.Empty)
                        {
                            hasValue = true;
                        }
                    }
                    if (hasValue)
                    {
                        dt.Rows.Add(dr);
                    }
                }
            }
            return dt;
        }
複製代碼

同時支持.xlsx和.xls

上面代碼用到了GetValueType函數:

複製代碼
        /// <summary>
        /// 獲取單元格類型
        /// </summary>
        /// <param name="cell">目標單元格</param>
        /// <returns></returns>
        private static object GetValueType(ICell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank:
                    return null;
                case CellType.Boolean:
                    return cell.BooleanCellValue;
                case CellType.Numeric:
                    return cell.NumericCellValue;
                case CellType.String:
                    return cell.StringCellValue;
                case CellType.Error:
                    return cell.ErrorCellValue;
                case CellType.Formula:
                default:
                    return "=" + cell.CellFormula;
            }
        }
複製代碼

最後是datatable寫入excel(僅適用於.xlsx)文件:

複製代碼
        /// <summary>
        /// Datable導出成Excel(xlsx)
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="file">導出路徑(包括文件名與擴展名)</param>
        public static void TableToExcel(DataTable dt, string file)
        {
            IWorkbook workbook;
            string fileExt = Path.GetExtension(file).ToLower();if (workbook == null) { return; }
            
            ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("sheet0") : workbook.CreateSheet(dt.TableName);
//表頭  
            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);
            }

            //數據  
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                IRow row1 = sheet.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    ICell cell = row1.CreateCell(j);
                    cell.SetCellValue(dt.Rows[i][j].ToString());
                }
            }
            //轉爲字節數組  
            MemoryStream stream = new MemoryStream();
            workbook.Write(stream);
            var buf = stream.ToArray();

            //保存爲Excel文件  
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Write))
            {
                fs.Write(buf, 0, buf.Length);
                fs.Flush();
            }

        }
複製代碼

其中:

using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Write))

這一行,FileMode.open會在已有的文件中加入你所create的sheet,適用FileMode.create會創新新文件,幾遍已有文件,也會刪掉該文件。

 

這是寫入.xls文件的代碼

複製代碼
        /// <summary>
        /// 將datatable寫入到excel(xls)
        /// </summary>
        /// <param name="dt">datatable</param>
        /// <param name="filepath">寫入的文件路徑</param>
        /// <returns></returns>
        public static bool DataTableToExcel(DataTable dt, string filepath)
        {
            bool result = false;
            IWorkbook workbook = null;
            FileStream fs = null;
            IRow row = null;
            ISheet sheet = null;
            ICell cell = null;
            try
            {
                if (dt != null && dt.Rows.Count > 0)
                {
                    workbook = new HSSFWorkbook();
                    sheet = workbook.CreateSheet("Sheet0");//創建一個名稱爲Sheet0的表  
                    int rowCount = dt.Rows.Count;//行數  
                    int columnCount = dt.Columns.Count;//列數  

                    int cellnum;

                    //設置列頭  
                    row = sheet.CreateRow(0);//excel第一行設爲列頭  
                    for (int c = 0; c < columnCount; c++)
                    {
                        cell = row.CreateCell(c);
                        cell.SetCellValue(dt.Columns[c].ColumnName);
                    }

                    //設置每行每列的單元格,  
                    for (int i = 0; i < rowCount; i++)
                    {
                        row = sheet.CreateRow(i + 1);
                        for (int j = 0; j < columnCount; j++)
                        {
                            cell = row.CreateCell(j);//excel第二行開始寫入數據
                            //cell.SetCellValue(dt.Rows[i][j].ToString());

                            //保存單元格格式爲數字
                            if (j < 2)
                            {
                                cell.SetCellValue(dt.Rows[i][j].ToString());
                            }
                            else
                            {
                                //cell.SetCellValue(int.Parse(dt.Rows[i][j].ToString()));
                                if (dt.Rows[i][j] is DBNull)
                                {
                                    cell.SetCellValue(dt.Rows[i][j].ToString());
                                }
                                else
                                {
                                    cellnum = Convert.ToInt32(dt.Rows[i][j].ToString());
                                    cell.SetCellValue(cellnum);
                                }
                            }
                        }
                    }
                    if (System.IO.File.Exists(filepath))
                    {
                        if (MessageBox.Show("該文件已存在!確定覆蓋嗎?", "WARNING", MessageBoxButtons.OKCancel) == DialogResult.OK)
                        {
                            File.Delete(filepath);
                        }
                        else
                        {
                            return false;
                        }

                    }
                    using (fs = File.OpenWrite(filepath))
                    {
                        workbook.Write(fs);//向打開的這個xls文件中寫入數據
                        result = true;
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                if (fs != null)
                {
                    fs.Close();
                }
                return false;
            }
        }
複製代碼

 

最後,雖然不常用,但是關鍵時刻很有用的,寫入文件時設置每個單元格數據類型的代碼:

複製代碼
        /// <summary>
        /// 設置單元格數據類型
        /// </summary>
        /// <param name="cell">目標單元格</param>
        /// <param name="obj">數據值</param>
        /// <returns></returns>
        public static void SetCellValue(ICell cell, object obj)
        {
            if (obj.GetType() == typeof(int))
            {
                cell.SetCellValue((int)obj);
            }
            else if (obj.GetType() == typeof(double))
            {
                cell.SetCellValue((double)obj);
            }
            else if (obj.GetType() == typeof(IRichTextString))
            {
                cell.SetCellValue((IRichTextString)obj);
            }
            else if (obj.GetType() == typeof(string))
            {
                cell.SetCellValue(obj.ToString());
            }
            else if (obj.GetType() == typeof(DateTime))
            {
                cell.SetCellValue((DateTime)obj);
            }
            else if (obj.GetType() == typeof(bool))
            {
                cell.SetCellValue((bool)obj);
            }
            else
            {
                cell.SetCellValue(obj.ToString());
            }
        }
複製代碼

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章