1. 程式人生 > >C#讀取Excel以及將資料匯入至Excel

C#讀取Excel以及將資料匯入至Excel

一,讀取Excel檔案內容:

//根據excle的路徑把第一個sheel中的內容放入datatable
    public static DataTable ReadExcelToTable()//excel存放的路徑
    {
        //連線字串
        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及以上版本 不能出現多餘的空格 而且分號注意
        //string connstring = Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';"; //Office 07以下版本 
        using (OleDbConnection conn = new OleDbConnection(connstring))
        {
            conn.Open();
            DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" }); //得到所有sheet的名字
            string firstSheetName = sheetsName.Rows[0][2].ToString(); //得到第一個sheet的名字
            string sql = string.Format("SELECT * FROM [{0}]", firstSheetName); //查詢字串
            //string sql = string.Format("SELECT * FROM [{0}] WHERE [日期] is not null", firstSheetName); //查詢字串
            OleDbDataAdapter ada = new OleDbDataAdapter(sql, connstring);
            DataSet set = new DataSet();
            ada.Fill(set);
            return set.Tables[0];
        }
    } 

二,將資料匯入至Excel:

protected void Excel1_Click(object sender, EventArgs e) {
        //設定儲存的文件型別
        //Response.ContentType = "application/ms-word";//儲存為Word型別  
        Response.ContentType = "application/ms-excel";//儲存為Excel型別
        //設定編碼方式和內容儲存的形式
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        Response.Charset = "Excel文件";
        //設定儲存為的檔名
        string dateStr = DateTime.Now.ToString("yyyyMMddHHmmss");
        string fileName = System.Web.HttpUtility.UrlEncode("料號檔案" + dateStr, System.Text.Encoding.UTF8);
        Response.AppendHeader("content-disposition", "attachment;filename=\"" + fileName + ".xls\"");
        //開始匯出;
        this.EnableViewState = false;
        StringWriter oStringWriter = new StringWriter();
        HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
        GridView1.RenderControl(oHtmlTextWriter);
        Response.Write(oStringWriter.ToString());
        oStringWriter = new StringWriter();
        oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
        GridView1.RenderControl(oHtmlTextWriter);
        Response.Write(oStringWriter.ToString());
        Response.End();   
    }
	//新增以下函式防止出現:“Gridview控制元件需在Runat=server中”  的異常
    public override void VerifyRenderingInServerForm(Control control)
    {
        //base.VerifyRenderingInServerForm(control);
    }
三,WinForm將DataGridView資料匯出至EXCEL
private void button2_Click(object sender, EventArgs e)
        {
            ToExcel();            
        }
        public void ToExcel()
        {
            try
            {
                //沒有資料的話就不往下執行  
                if (dataGridView1.Rows.Count == 0)
                    return;
                //例項化一個Excel.Application物件  
                Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
                //讓後臺執行設定為不可見,為true的話會看到開啟一個Excel,然後資料在往裡寫  
                excel.Visible = true;
                //新增加一個工作簿,Workbook是直接儲存,不會彈出儲存對話方塊,加上Application會彈出儲存對話方塊,值為false會報錯  
                excel.Application.Workbooks.Add(true);
                //生成Excel中列頭名稱  
                for (int i = 0; i < dataGridView1.Columns.Count; i++)
                {
                    if (this.dataGridView1.Columns[i].Visible == true)
                    {
                        excel.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;
                    }

                }
                //把DataGridView當前頁的資料儲存在Excel中  
                for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
                {
                    System.Windows.Forms.Application.DoEvents();
                    for (int j = 0; j < dataGridView1.Columns.Count; j++)
                    {
                        if (this.dataGridView1.Columns[j].Visible == true)
                        {
                            if (dataGridView1[j, i].ValueType == typeof(string))
                            {
                                excel.Cells[i + 2, j + 1] = "'" + dataGridView1[j, i].Value.ToString();
                            }
                            else
                            {
                                excel.Cells[i + 2, j + 1] = dataGridView1[j, i].Value.ToString();
                            }
                        }

                    }
                }
                //設定禁止彈出儲存和覆蓋的詢問提示框  
                excel.DisplayAlerts = false;
                excel.AlertBeforeOverwriting = false;
                //儲存工作簿  
                excel.Application.Workbooks.Add(true).Save();
                //儲存excel檔案  
                excel.Save("E:\\Peng.Tao\\Winform\\MyFirstWinform" + "\\Data.xls");
                //確保Excel程序關閉  
                excel.Quit();
                excel = null;
                GC.Collect();//如果不使用這條語句會導致excel程序無法正常退出,使用後正常退出
                MessageBox.Show(this, "檔案已經成功匯出!", "資訊提示");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "錯誤提示");
            }
        }