C#讀取excel文件,並生成json


這次介紹兩種方法,第一種是安裝AccessDatabaseEngine,第二種是利用Npoi讀取excel

一、第一種利用AccessDatabaseEngine進行讀取excel文件

1.安裝AccessDatabaseEngine

鏈接地址:http://download.microsoft.com/download/7/0/3/703ffbcb-dc0c-4e19-b0da-1463960fdcdb/AccessDatabaseEngine.exe

2.根據Excel文件獲取所有的Sheet名稱,獲取每一個sheet的內容組裝dataTable

(1)根據Excel文件獲取所有的sheet名稱

 public List<string> GetExcelSheetNames(string filePath)
        {
            OleDbConnection connection = null;
            System.Data.DataTable dt = null;
            try
            {
                String connectionString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=YES;IMEX=2;'", filePath);
                connection = new OleDbConnection(connectionString);
                connection.Open();
                dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                if (dt == null)
                {
                    return new List<string>();
                }

                String[] excelSheets = new String[dt.Rows.Count];
                int i = 0;
                foreach (DataRow row in dt.Rows)
                {
                    excelSheets[i] = row["TABLE_NAME"].ToString().Split('$')[0];
                    i++;
                }
                return excelSheets.Distinct().ToList();
            }
            catch (Exception ex)
            {
                return new List<string>();
            }
            finally
            {
                if (connection != null)
                {
                    connection.Close();
                    connection.Dispose();
                }
                if (dt != null)
                {
                    dt.Dispose();
                }
            }
        }

(2)獲取每一個Sheet的內容組裝dataTable

public DataTable GetExcelContent(String filePath, string sheetName)
        {
            if (sheetName == "_xlnm#_FilterDatabase")
                return null;
            DataSet dateSet = new DataSet();
            String connectionString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=NO;IMEX=2;'", filePath);
            String commandString = string.Format("SELECT * FROM [{0}$]", sheetName);
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                connection.Open();
                using (OleDbCommand command = new OleDbCommand(commandString, connection))
                {
                    OleDbCommand objCmd = new OleDbCommand(commandString, connection);
                    OleDbDataAdapter myData = new OleDbDataAdapter(commandString, connection);
                    myData.Fill(dateSet, sheetName);
                    DataTable table = dateSet.Tables[sheetName];
                    for (int i = 0; i < table.Rows[0].ItemArray.Length; i++)
                    {
                        var cloumnName = table.Rows[0].ItemArray[i].ToString();
                        if (!string.IsNullOrEmpty(cloumnName))
                            table.Columns[i].ColumnName = cloumnName;
                    }
                    table.Rows.RemoveAt(0);
                    return table;
                }
            }
        }

(3)table轉json

 public object ExcelToJson(string filePath)
        {
            string localPath = Server.MapPath(filePath);            
            List<string> tableNames = GetExcelSheetNames(localPath);
            var json = new JObject();
            tableNames.ForEach(tableName =>
            {
                var table = new JArray() as dynamic;
                DataTable dataTable = GetExcelContent(localPath, tableName);
                foreach (DataRow dataRow in dataTable.Rows)
                {
                    dynamic row = new JObject();
                    foreach (DataColumn column in dataTable.Columns)
                    {
                        row.Add(column.ColumnName, dataRow[column.ColumnName].ToString());
                    }
                    table.Add(row);
                }
                json.Add(tableName, table);
            });
            return json.ToString();
        }

最終生成的字符串:

二、利用NPOI讀取excel

1.將excel文件中的內容讀取出來,存放到DataSet中

#region 將Excel中的內容轉換成DataSet
        /// <summary>
        /// 將Excel中的內容轉換成DataSet
        /// </summary>
        /// <param name="filePath">路徑</param>
        /// <param name="excelHeader">第一行的文本</param>
        /// <returns></returns>
        public static DataSet ImportExcelToDataSet(string filePath,List<string> excelHead)
        {           
            DataSet ds = new DataSet();
            IWorkbook workbook;
            string fileExt = Path.GetExtension(filePath).ToLower();
            try
            {
                using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    if (fileExt == ".xlsx")
                    {
                        workbook = new XSSFWorkbook(fs);//2007之后版本的excel
                    }
                    else
                    {
                        workbook = new HSSFWorkbook(fs);//2003版本的excel
                    }
                    for (int a = 0, b = workbook.NumberOfSheets; a < b; a++)
                    {
                        //獲取讀取的Sheet表的索引
                        ISheet sheet = workbook.GetSheetAt(a);
                        DataTable table = new DataTable();
                        IRow headerRow = sheet.GetRow(sheet.FirstRowNum);
                        int cellCount = headerRow.LastCellNum;
                        //將第一行的文本作為列名
                        for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                        {
                            DataColumn column;
                            object obj = GetValueType(headerRow.GetCell(i));
                            if (obj == null || obj.ToString() == string.Empty)
                            {
                                column = new DataColumn("Columns" + i.ToString());
                            }  
                 else{
                                column = new DataColumn(GetType(obj.ToString())); 
}
 table.Columns.Add(column); } //讀取第一行下面的數據,將他們作為數據行存儲
                        for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); if (row == null || row.GetCell(0) == null || row.GetCell(0).ToString().Trim() == "") { // 如果遇到第一個空行,跳出本次循環,繼續向下讀取 
                                continue; } DataRow dataRow = table.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++) { if (row.GetCell(j) != null) { dataRow[j] = row.GetCell(j).ToString(); } } table.Rows.Add(dataRow); } ds.Tables.Add(table); } workbook = null; return ds; } } catch (Exception ex) { return ds; } } #endregion
 

注意:這是獲取單元格類型的方法

 #region 獲取單元格類型
        /// <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:  
                    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;
            }
        }
        #endregion

2.將DataTable轉換成對應的list對象

 #region DataTable內容轉成List
        /// <summary>
        /// 將Excel中的內容轉換成List
        /// </summary>
        /// <param name="filePath">文件路徑</param>
        /// <returns></returns>
        public static List<CompanyMobileViewModel> CompanyList(string filePath)
        {
            List<CompanyMobileViewModel> mobileList = new List<CompanyMobileViewModel>();
            try
            {
                //獲取excel中的內容
                var excelData = ImportExcelToDataSet(filePath,SetPhoneHeader());                //遍歷DataSet
                if (excelData.Tables.Count < 1)
                {
                    return mobileList;
                }
                foreach (DataTable dt in excelData.Tables)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        for(var i=0;i<dr.ItemArray.Length;i++)
                        {
                            //驗證是否包含特殊字符
                            if (dr.ItemArray[i].ToString() != "" && GBCustomsHelper.ValidateSymbol(dr.ItemArray[i].ToString()) == true)
                            {
                                mobileList.Add(new CompanyMobileViewModel()
                                {
                                    CompanyID = "js",                                  
                                });
                                return mobileList;
                            }
                        }                    
                        mobileList.Add(new CompanyMobileViewModel()
                        {
                            CompanyID = dr.ItemArray[0].ToString(),
                            MobileBusiness = dr.ItemArray[1].ToString(),
                            MobileStatutory = dr.ItemArray[2].ToString(),
                            State = 0,
                        });
                    }
                }
                return mobileList;//然后再用一個方法接收這個返回值,這樣excel的內容就讀取出來了
            }
            catch (Exception ex)
            {                
                return mobileList;
            }
        }
        #endregion

3.將list對象轉換成json,傳遞到前端

 #region 將上傳的excel中的內容轉換成json
        /// <summary>
        /// 將上傳的excel中的內容轉換成json
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public object ExcelToJson(string filePath)
        {
            //數據總表
            List<CompanyMobileViewModel> mobileView = CompanyList(filePath);
       var jsonData=new{Rows=mobileView,Total=mobileView.Count()};
       return Json(jsonData,JsonRequestBehavior.AllowGet);
}

對於這兩種方法,個人感覺第二種利用NPOI讀取excel更方便,不用在安裝軟件,省去很多的麻煩

本文參考:https://blog.csdn.net/xiaoxiao520c/article/details/77962326

整理之后,留着以后復習用的,如有問題,請留言


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM