C#讀取Excel以及將數據導入至Excel

一,讀取Excel文件內容:

 1 //根據excle的路徑把第一個sheel中的內容放入datatable 
 2     public static DataTable ReadExcelToTable()//excel存放的路徑 
 3  {  4         //鏈接字符串 
 5         string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "E:/Peng.Tao/TEST/1.xlsx" + ";Extended Properties='Excel8.0;HDR=NO;IMEX=1';"; // Office 07及以上版本 不能出現多餘的空格 並且分號注意  6         //string connstring = Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';"; //Office 07如下版本 
 7         using (OleDbConnection conn = new OleDbConnection(connstring))  8  {  9  conn.Open(); 10             DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" }); //獲得全部sheet的名字 
11             string firstSheetName = sheetsName.Rows[0][2].ToString(); //獲得第一個sheet的名字 
12             string sql = string.Format("SELECT * FROM [{0}]", firstSheetName); //查詢字符串 13             //string sql = string.Format("SELECT * FROM [{0}] WHERE [日期] is not null", firstSheetName); //查詢字符串 
14             OleDbDataAdapter ada = new OleDbDataAdapter(sql, connstring); 15             DataSet set = new DataSet(); 16             ada.Fill(set); 17             return set.Tables[0]; 18  } 19     }

二,將數據導入至Excel:

 1 protected void Excel1_Click(object sender, EventArgs e) {  2         //設置保存的文檔類型  3         //Response.ContentType = "application/ms-word";//保存爲Word類型 
 4         Response.ContentType = "application/ms-excel";//保存爲Excel類型  5         //設置編碼方式和內容保存的形式 
 6         Response.ContentEncoding = System.Text.Encoding.UTF8;  7         Response.Charset = "Excel文檔";  8         //設置保存爲的文件名 
 9         string dateStr = DateTime.Now.ToString("yyyyMMddHHmmss"); 10         string fileName = System.Web.HttpUtility.UrlEncode("料號文件" + dateStr, System.Text.Encoding.UTF8); 11         Response.AppendHeader("content-disposition", "attachment;filename=\"" + fileName + ".xls\""); 12         //開始導出; 
13         this.EnableViewState = false; 14         StringWriter oStringWriter = new StringWriter(); 15         HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter); 16  GridView1.RenderControl(oHtmlTextWriter); 17  Response.Write(oStringWriter.ToString()); 18         oStringWriter = new StringWriter(); 19         oHtmlTextWriter = new HtmlTextWriter(oStringWriter); 20  GridView1.RenderControl(oHtmlTextWriter); 21  Response.Write(oStringWriter.ToString()); 22  Response.End(); 23  } 24     //添加如下函數防止出現:「Gridview控件需在Runat=server中」 的異常 
25     public override void VerifyRenderingInServerForm(Control control) 26  { 27         //base.VerifyRenderingInServerForm(control); 
28     }

三,WinForm將DataGridView數據導出至EXCEL

 1 private void button2_Click(object sender, EventArgs e)  2  {  3  ToExcel();  4  }  5         public void ToExcel()  6  {  7             try  
 8  {  9                 //沒有數據的話就不往下執行 
10                 if (dataGridView1.Rows.Count == 0) 11                     return; 12                 //實例化一個Excel.Application對象 
13                 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); 14                 //讓後臺執行設置爲不可見,爲true的話會看到打開一個Excel,而後數據在往裏寫 
15                 excel.Visible = true; 16                 //新增長一個工做簿,Workbook是直接保存,不會彈出保存對話框,加上Application會彈出保存對話框,值爲false會報錯 
17                 excel.Application.Workbooks.Add(true); 18                 //生成Excel中列頭名稱 
19                 for (int i = 0; i < dataGridView1.Columns.Count; i++) 20  { 21                     if (this.dataGridView1.Columns[i].Visible == true) 22  { 23                         excel.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText; 24  } 25   
26  } 27                 //把DataGridView當前頁的數據保存在Excel中 
28                 for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) 29  { 30  System.Windows.Forms.Application.DoEvents(); 31                     for (int j = 0; j < dataGridView1.Columns.Count; j++) 32  { 33                         if (this.dataGridView1.Columns[j].Visible == true) 34  { 35                             if (dataGridView1[j, i].ValueType == typeof(string)) 36  { 37                                 excel.Cells[i + 2, j + 1] = "'" + dataGridView1[j, i].Value.ToString(); 38  } 39                             else  
40  { 41                                 excel.Cells[i + 2, j + 1] = dataGridView1[j, i].Value.ToString(); 42  } 43  } 44   
45  } 46  } 47                 //設置禁止彈出保存和覆蓋的詢問提示框 
48                 excel.DisplayAlerts = false; 49                 excel.AlertBeforeOverwriting = false; 50                 //保存工做簿 
51                 excel.Application.Workbooks.Add(true).Save(); 52                 //保存excel文件 
53                 excel.Save("E:\\Peng.Tao\\Winform\\MyFirstWinform" + "\\Data.xls"); 54                 //確保Excel進程關閉 
55  excel.Quit(); 56                 excel = null; 57                 GC.Collect();//若是不使用這條語句會致使excel進程沒法正常退出,使用後正常退出 
58                 MessageBox.Show(this, "文件已經成功導出!", "信息提示"); 59  } 60             catch (Exception ex) 61  { 62                 MessageBox.Show(ex.Message, "錯誤提示"); 63  } 64         }
相關文章
相關標籤/搜索