C# 各種匯入 Excel 檔案的資料的方法總結

來源:互聯網
上載者:User

標籤:log   指定   cli   資料   cat   虛擬   source   aac   span   

在匯入之前都需要將上傳的檔案儲存到伺服器,所以避免重複的寫這些代碼,先貼出上傳檔案並儲存到伺服器指定路徑的代碼。

protected void btnImport_Click(object sender, EventArgs e)        {            Random random = new Random();            ImportClass Import = new ImportClass();            //儲存檔案的虛擬路徑            string path = "Import/";            //擷取選擇的檔案名稱            string fileName = FileUpload1.FileName;            //擷取副檔名稱            string fileExt = Path.GetExtension(fileName);            //產生新檔案名稱            string newName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + random.Next(0, 9999).ToString();            //擷取指定虛機路徑的實體路徑            string fullPath = HttpContext.Current.Server.MapPath(path);            //上傳檔案儲存路徑            string savePath = fullPath + newName + fileExt;            //儲存檔案到伺服器            FileUpload1.SaveAs(savePath);            try            {                //擷取匯入的資料                DataSet ds = Import.ImportExcel(savePath);                if (ds != null && ds.Tables.Count > 0)                {                    //這裡可以寫插入資料庫的方法                }            }            catch (Exception ex)            {                throw;            }        }
View Code

第一種:OleDB

public DataSet ImportExcel(string filePath)        {            DataSet ds = null;            OleDbConnection conn;            string strConn = string.Empty;            string sheetName = string.Empty;            try            {                // Excel 2003 版本連接字串                strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=‘Excel 8.0; HDR=YES; IMEX=1;‘";                conn = new OleDbConnection(strConn);                conn.Open();            }            catch            {                // Excel 2007 以上版本連接字串                strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=‘Excel 12.0;HDR=Yes;IMEX=1;‘";                conn = new OleDbConnection(strConn);                conn.Open();            }            //擷取所有的 sheet 表            DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });            ds = new DataSet();            for (int i = 0; i < dtSheetName.Rows.Count; i++)            {                DataTable dt = new DataTable();                dt.TableName = "table" + i.ToString();                //擷取表名                sheetName = dtSheetName.Rows[i]["TABLE_NAME"].ToString();                OleDbDataAdapter oleda = new OleDbDataAdapter("select * from [" + sheetName + "]", conn);                oleda.Fill(dt);                ds.Tables.Add(dt);            }            return ds;        }
View Code

除了讀取過程不太靈活之外,這種讀取方式還有個弊端就是,當 Excel 資料量很大時。會非常佔用記憶體,當記憶體不夠時會拋出記憶體溢出的異常,不過一般都能適用了。

 

第二種:Microsoft.Office.Interop.Excel.dll

public DataSet ImportExcel(string filePath)        {            DataSet ds = null;            DataTable dt = null;            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();            Microsoft.Office.Interop.Excel.Workbook workbook = null;            Microsoft.Office.Interop.Excel.Worksheet worksheet = null;            Microsoft.Office.Interop.Excel.Sheets sheets = null;            Microsoft.Office.Interop.Excel.Range range = null;            object missing = System.Reflection.Missing.Value;            try            {                if (excel == null)                {                    return null;                }                //開啟 Excel 檔案                workbook = excel.Workbooks.Open(filePath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);                //擷取所有的 sheet 表                sheets = workbook.Worksheets;                ds = new DataSet();                for (int i = 1; i <= sheets.Count; i++)                {                    //擷取第一個表                    worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(i);                    int rowCount = worksheet.UsedRange.Rows.Count;                    int colCount = worksheet.UsedRange.Columns.Count;                    int rowIndex = 1;   //起始行為 1                    int colIndex = 1;   //起始列為 1                    DataColumn dc;                    dt = new DataTable();                    dt.TableName = "table" + i.ToString();                    //讀取列名                    for (int j = 0; j < colCount; j++)                    {                        range = worksheet.Cells[rowIndex, colIndex + j];                        dc = new DataColumn();                        dc.DataType = Type.GetType("System.String");                        dc.ColumnName = range.Text.ToString().Trim();                        //添加列                        dt.Columns.Add(dc);                    }                    //讀取行資料                    for (int k = 1; k < rowCount; k++)                    {                        DataRow dr = dt.NewRow();                        for (int l = 0; l < colCount; l++)                        {                            range = worksheet.Cells[rowIndex + k, colIndex + l];                            //使用 range.Value.ToString(); 或 range.Value2.ToString(); 或 range.Text.ToString(); 都可以擷取儲存格的值                            dr[l] = range.Text.ToString();                        }                        dt.Rows.Add(dr.ItemArray);                    }                    ds.Tables.Add(dt);                }            }            catch (Exception ex)            {                throw;            }            return ds;        }
View Code

這種方法首先需要安裝有 office Excel,並且是一個儲存格一個儲存格的讀取,所以效能會比較差。

 

未完待續。。。

C# 各種匯入 Excel 檔案的資料的方法總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.