C#——使用NPOI操作Excel以及CSV

    class ExcelHelper
    {
        /// <summary>  
        /// 將excel導入到datatable  
        /// </summary>  
        /// <param name="filePath">excel路徑</param>  
        /// <param name="isColumnName">第一行是否是列名</param>  
        /// <returns>返回datatable</returns>  
        public static DataTable ExcelToDataTable(bool isColumnName, string filePath = "")
        {
            DataTable dataTable = null;
            FileStream fs = null;
            DataColumn column = null;
            DataRow dataRow = null;
            if (filePath == "")
            {
                System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
                ofd.Filter = "Excel 2007-13文件(*.xlsx)|*.xlsx|Excel 2003文件(*.xls)|*.xls";
                if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    filePath = ofd.FileName;
                }
                else
                {
                    return null;
                }
            }
            IWorkbook workbook = null;
            ISheet sheet = null;
            IRow row = null;
            int startRow = 0;
            try
            {
                using (fs = File.OpenRead(filePath))
                {
                    // 2007版本  
                    if (filePath.IndexOf(".xlsx") > 0)
                        workbook = new XSSFWorkbook(fs);
                    // 2003版本  
                    else if (filePath.IndexOf(".xls") > 0)
                        workbook = new HSSFWorkbook(fs);

                    if (workbook != null)
                    {
                        int sheetnum = workbook.NumberOfSheets;
                        for (int s = 0; s < sheetnum; s++)
                        {
                            sheet = workbook.GetSheetAt(s);
                            if (s == 0)
                            {
                                dataTable = new DataTable();
                                if (sheet != null)
                                {
                                    int rowCount = sheet.LastRowNum;//總行數  
                                    if (rowCount > 0)
                                    {
                                        IRow firstRow = sheet.GetRow(0);//第一行  
                                        IRow header = sheet.GetRow(sheet.FirstRowNum);
                                        int cellCount = firstRow.LastCellNum;//列數  
                                        List<int> columns = new List<int>();
                                        //構建datatable的列  
                                        if (isColumnName)
                                        {
                                            startRow = 1;//如果第一行是列名,則從第二行開始讀取  
                                            for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                            {
                                                object obj = GetValueType(header.GetCell(i));
                                                if (obj == null || obj.ToString() == string.Empty)
                                                {
                                                    dataTable.Columns.Add(new DataColumn("Columns" + i.ToString()));
                                                }
                                                else
                                                {
                                                    dataTable.Columns.Add(new DataColumn(obj.ToString()));
                                                }
                                                columns.Add(i);
                                            }
                                        }
                                        else
                                        {
                                            for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                            {
                                                column = new DataColumn("column" + (i + 1));
                                                dataTable.Columns.Add(column);
                                            }
                                        }

                                        //填充行  
                                        for (int i = startRow; i <= rowCount; ++i)
                                        {
                                            row = sheet.GetRow(i);
                                            if (row == null) continue;

                                            dataRow = dataTable.NewRow();
                                            bool hasValue = false;
                                            foreach (int j in columns)
                                            {
                                                dataRow[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                                                if (dataRow[j] != null && dataRow[j].ToString() != string.Empty)
                                                {
                                                    hasValue = true;
                                                }
                                            }
                                            if (hasValue)
                                            {
                                                dataTable.Rows.Add(dataRow);
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                isColumnName = false;
                                if (sheet != null)
                                {
                                    int rowCount = sheet.LastRowNum;//總行數  
                                    if (rowCount > 0)
                                    {
                                        IRow firstRow = sheet.GetRow(0);//第一行  
                                        IRow header = sheet.GetRow(sheet.FirstRowNum);
                                        int cellCount = firstRow.LastCellNum;//列數

                                        //填充行  
                                        for (int i = 1; i <= rowCount; ++i)
                                        {
                                            row = sheet.GetRow(i);
                                            if (row == null) continue;

                                            dataRow = dataTable.NewRow();
                                            bool hasValue = false;
                                            for (int j = 0; j < dataTable.Columns.Count; j++)
                                            {
                                                dataRow[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                                                if (dataRow[j] != null && dataRow[j].ToString() != string.Empty)
                                                {
                                                    hasValue = true;
                                                }
                                            }
                                            if (hasValue)
                                            {
                                                dataTable.Rows.Add(dataRow);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                return dataTable;
            }
            catch (Exception)
            {
                if (fs != null)
                {
                    fs.Close();
                }
                return null;
            }
        }

        /// <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: //BLANK:  
                    return null;
                case CellType.Boolean: //BOOLEAN:  
                    return cell.BooleanCellValue;
                case CellType.Numeric: //NUMERIC: 
                    if (DateUtil.IsCellDateFormatted(cell))
                    {
                        return cell.DateCellValue;
                    }
                    else
                    {
                        return cell.NumericCellValue;
                    }
                    short format = cell.CellStyle.DataFormat;
                    if (format != 0) { return cell.DateCellValue; } else { return cell.NumericCellValue; }
                case CellType.String: //STRING:  
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:  
                    return cell.ErrorCellValue;
                case CellType.Formula: //FORMULA:  
                default:
                    return "=" + cell.CellFormula;
            }
        }

        /// <summary>
        /// Datable導出成Excel
        /// </summary>
        /// <param name="dt">需要導出的datatable</param>
        /// <param name="file">導出路徑(包括文件名與擴展名)</param>
        public static void DataTableToExcel(DataTable dt, string file = "", bool isShowResult = true)
        {
            IWorkbook workbook;
            if (file == "")
            {
                System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog();
                sfd.Filter = "Excel 2007-13文件(*.xlsx)|*.xlsx|Excel 2003文件(*.xls)|*.xls";
                sfd.DefaultExt = "xlsx";
                sfd.AddExtension = true;
                if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    file = sfd.FileName;
                }
                else
                {
                    return;
                }
            }

            string fileExt = Path.GetExtension(file).ToLower();
            if (fileExt == ".xlsx")
            {
                workbook = new XSSFWorkbook();
            }
            else if (fileExt == ".xls")
            {
                workbook = new HSSFWorkbook();
            }
            else
            {
                workbook = null;
            }
            if (workbook == null)
            {
                return;
            }
            ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : 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.Create, FileAccess.Write))
            {
                fs.Write(buf, 0, buf.Length);
                fs.Flush();
                if (isShowResult)
                {
                    System.Windows.MessageBox.Show("保存成功!");
                }
            }
        }
    }
    public class CSVHelper
    {
        /// <summary>
        /// 寫入CSV文件
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="fileName">文件全名</param>
        /// <returns>是否寫入成功</returns>
        public static bool SaveCSV(DataTable dt, string fullFileName = "")
        {
            if (fullFileName == "")
            {
                System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog();
                sfd.Filter = "CSV文件(*.csv)|*.csv";
                sfd.DefaultExt = "csv";
                if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    fullFileName = sfd.FileName;
                }
                else
                {
                    return false;
                }
            }
            try
            {
                FileStream fs = new FileStream(fullFileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
                string data = "";

                //寫出列名稱
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    data += dt.Columns[i].ColumnName.ToString();
                    if (i < dt.Columns.Count - 1)
                    {
                        data += ",";
                    }
                }
                sw.WriteLine(data);

                //寫出各行數據
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    data = "";
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        data += dt.Rows[i][j].ToString();
                        if (j < dt.Columns.Count - 1)
                        {
                            data += ",";
                        }
                    }
                    sw.WriteLine(data);
                }

                sw.Close();
                fs.Close();

                return true;
            }
            catch (Exception e)
            {
                System.Windows.MessageBox.Show(e.Message);
                return false;
            }

        }

        /// <summary>
        /// 打開CSV 文件
        /// </summary>
        /// <param name="fileName">文件全名</param>
        /// <returns>DataTable</returns>
        public static DataTable OpenCSV(string fileName = "")
        {
            if (fileName == "")
            {
                System.Windows.MessageBox.Show("目標CSV文件不存在,請手動選擇數據文件.");
                System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
                ofd.Filter = "CSV文件(*.csv)|*.csv";
                ofd.DefaultExt = "csv";
                if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    fileName = ofd.FileName;
                    return OpenCSV(fileName, 0, 0, 0, 0, true);
                }
                else
                {
                    return null;
                }
            }
            else
            {
                try
                {
                    return OpenCSV(fileName, 0, 0, 0, 0, true);
                }
                catch (Exception e)
                {
                    System.Windows.MessageBox.Show(e.Message);
                    return null;
                }

            }
        }

        /// <summary>
        /// 打開CSV 文件
        /// </summary>
        /// <param name="fileName">文件全名</param>
        /// <param name="firstRow">開始行</param>
        /// <param name="firstColumn">開始列</param>
        /// <param name="getRows">獲取多少行</param>
        /// <param name="getColumns">獲取多少列</param>
        /// <param name="haveTitleRow">是有標題行</param>
        /// <returns>DataTable</returns>
        public static DataTable OpenCSV(string fullFileName, Int16 firstRow = 0, Int16 firstColumn = 0, Int16 getRows = 0, Int16 getColumns = 0, bool haveTitleRow = true)
        {
            DataTable dt = new DataTable();
            FileStream fs = new FileStream(fullFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);
            //記錄每次讀取的一行記錄
            string strLine = "";
            //記錄每行記錄中的各字段內容
            string[] aryLine;
            //標示列數
            int columnCount = 0;
            //是否已建立了表的字段
            bool bCreateTableColumns = false;
            //第幾行
            int iRow = 1;

            //去除無用行
            if (firstRow > 0)
            {
                for (int i = 1; i < firstRow; i++)
                {
                    sr.ReadLine();
                }
            }

            // { ",", ".", "!", "?", ";", ":", " " };
            string[] separators = { "," };
            //逐行讀取CSV中的數據
            while ((strLine = sr.ReadLine()) != null)
            {
                strLine = strLine.Trim();
                aryLine = strLine.Split(separators, System.StringSplitOptions.RemoveEmptyEntries);

                if (bCreateTableColumns == false)
                {
                    bCreateTableColumns = true;
                    columnCount = aryLine.Length;
                    //創建列
                    for (int i = firstColumn; i < (getColumns == 0 ? columnCount : firstColumn + getColumns); i++)
                    {
                        DataColumn dc
                            = new DataColumn(haveTitleRow == true ? aryLine[i] : "COL" + i.ToString());
                        dt.Columns.Add(dc);
                    }

                    bCreateTableColumns = true;

                    if (haveTitleRow == true)
                    {
                        continue;
                    }
                }


                DataRow dr = dt.NewRow();
                //for (int j = firstColumn; j < (getColumns == 0 ? columnCount : firstColumn + getColumns); j++)
                //{
                //    dr[j - firstColumn] = aryLine[j];
                //}
                for (int j = firstColumn; j < aryLine.Length; j++)
                {
                    dr[j - firstColumn] = aryLine[j];
                }
                dt.Rows.Add(dr);

                iRow = iRow + 1;
                if (getRows > 0)
                {
                    if (iRow > getRows)
                    {
                        break;
                    }
                }

            }

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