2011-11-04 109 views
0

我需要打開現有的Excel文件並填寫DataTable。 我該怎麼做?將DataTable導出到現有的Excel

我在ASP.NET

工作

我已經嘗試這種解決方案創建一個Excel(http://stackoverflow.com/questions/1746701/export-datatable-to-excel-file) 然後我試圖像這樣一個OLEDB連接打開它,但它沒有工作..它說,該表是不正確的格式..然後它說,IR找不到ISAM文件..我不知道該怎麼辦..

System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;DataSource=C:\reports\report.xls;Extended Properties=""Excel 8.0;HDR=No;IMEX=1"""); 

conn.Open(); 
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(); 
cmd.Connection = conn; 

cmd.CommandText = @"SELECT * INTO [Excel 8.0;Database=C:\reports\reportBase.xls].[SheetBase1] FROM Sheet1]"; 

cmd.ExecuteNonQuery(); 
conn.Close(); 

請幫助我!我很絕望!!

謝謝!

+0

儘量按照這個線程。 http://stackoverflow.com/questions/1746701/export-datatable-to-excel-file 問候 –

回答

4

,如果你也有興趣在第三方Excel中的.NET庫,可以打開現有的Excel後文件,並與GemBox.Spreadsheet Excel C#/VB.NET庫的DataTable填充它。

這裏是一個Excel ASP.NET樣本如何打開現有的Excel文件,用一個DataTable填充它和它傳輸到瀏覽器:

DataTable people = (DataTable)Session["people"]; 

// Open excel file and insert data table. 
ExcelFile ef = new ExcelFile(); 
ef.LoadXls(Server.MapPath("MyData.xls")); 
ExcelWorksheet ws = ef.Worksheets[0]; 
ws.InsertDataTable(people, "A1", true); 

Response.Clear(); 

// Stream file to browser, in required type. 
switch (this.RadioButtonList1.SelectedValue) 
{ 
    case "XLS": 
     Response.ContentType = "application/vnd.ms-excel"; 
     Response.AddHeader("Content-Disposition", "attachment; filename=" + 
      "Report.xls"); 
     ef.SaveXls(Response.OutputStream); 
     break; 

    case "XLSX": 
     Response.ContentType = "application/vnd.openxmlformats"; 
     Response.AddHeader("Content-Disposition", "attachment; filename=" + 
      "Report.xlsx"); 
     // With XLSX it is a bit more complicated as MS Packaging API 
     // can't write directly to Response.OutputStream. 
     // Therefore we use temporary MemoryStream. 
     MemoryStream ms = new MemoryStream(); 
     ef.SaveXlsx(ms) 
     ms.WriteTo(Response.OutputStream); 
     break; 
} 
Response.End(); 
1

您可以使用此解決方案....只有讓你的數據到DataTable中....

protected void Button1_Click(object sender, EventArgs e) 
{ 
    DataTable dtRecords = new DataTable(); 
    dtRecords.Columns.Add("FIRSTNAME"); 
    dtRecords.Columns.Add("LASTNAME"); 
    dtRecords.Columns.Add("JOB"); 
    DataRow rw1 = dtRecords.NewRow(); 
    rw1[0] = "JHON"; 
    rw1[1] = "SMITH"; 
    rw1[2] = "MANAGER"; 
    dtRecords.Rows.Add(rw1); 
    DataRow rw2 = dtRecords.NewRow(); 
    rw2[0] = "MICH"; 
    rw2[1] = "KEN"; 
    rw2[2] = "SR MANAGER"; 
    dtRecords.Rows.Add(rw2); 

    UploadDataTableToExcel(dtRecords); 

} 
protected void UploadDataTableToExcel(DataTable dtRecords) 
{ 
     string XlsPath = Server.MapPath(@"~/Add_data/test.xls"); 
     string attachment = string.Empty; 
     if (XlsPath.IndexOf("\\") != -1) 
     { 
      string[] strFileName = XlsPath.Split(new char[] { '\\' }); 
      attachment = "attachment; filename=" + strFileName[strFileName.Length - 1]; 
     } 
     else 
      attachment = "attachment; filename=" + XlsPath; 
     try 
     { 
      Response.ClearContent(); 
      Response.AddHeader("content-disposition", attachment); 
      Response.ContentType = "application/vnd.ms-excel"; 
      string tab = string.Empty; 

      foreach (DataColumn datacol in dtRecords.Columns) 
      { 
       Response.Write(tab + datacol.ColumnName); 
       tab = "\t"; 
      } 
      Response.Write("\n"); 

      foreach (DataRow dr in dtRecords.Rows) 
      { 
       tab = ""; 
       for (int j = 0; j < dtRecords.Columns.Count; j++) 
       { 
        Response.Write(tab + Convert.ToString(dr[j])); 
        tab = "\t"; 
       } 

       Response.Write("\n"); 
      } 
      Response.End(); 
     } 
     catch (Exception ex) 
     { 
      //Response.Write(ex.Message); 
     } 
} 
+0

這是創建一個新的Excel。我需要寫上現有的Excel在響應我的光盤。 – Nicole

0

,如果你也有興趣在第三方Excel中.NET圖書館,你可以打開現有的Excel文件,並與GemBox.Spreadsheet Excel的C#/ VB.NET庫的DataTable填充它。

另外,如果你要花費$ 480的許可,您可以下載我的導出到Excel C#類完全免費的。

它使用的OpenXML庫來創建一個真正的Excel 2007中的文件,你只需要指定一個文件名,並稱之爲「CreateExcelDocument」功能。

DataSet ds = CreateSampleData(); 
string excelFilename = "C:\\Sample.xlsx"; 
CreateExcelFile.CreateExcelDocument(ds, excelFilename); 

您可以從一個DataSet,DataTable中或列表<創建Excel文件>。

所有的源代碼提供,完全免費的,在我的網頁,以及說明和演示項目:

http://mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm

甚至還有一些示例代碼,展示瞭如何創建您的Excel文件一個ASP.Net應用程序,然後打開它。

祝你好運!

0

我用這個belove代碼得到了準確的結果.....

這可能會幫助你..

try 
     { 


      if (dt == null || dt.Columns.Count == 0) 
      { 
       throw new Exception("ExportToExcel: Null or empty input table!\n"); 
      } 
      string Filepath = "E:Sample\\Form.xlsx"; 
      string SheetName = "Elnath - 3000"; 
      // Microsoft.Office.Interop.Excel.Application xlApp; 
      Microsoft.Office.Interop.Excel.Workbook xlWorkBook; 
      Microsoft.Office.Interop.Excel._Worksheet xlWorkSheet; 
      // Microsoft.Office.Interop.Excel.Range xlRange = null; 
      object misValue = Type.Missing; 

      Excel.Application xlApp = new Excel.Application(); 
      xlWorkBook = xlApp.Workbooks.Add(Filepath); 

      // xlWorkBook = xlApp.Workbooks.Open(Filepath, misValue, false, misValue, misValue, misValue, true, misValue, misValue, misValue, misValue, misValue, false, misValue, misValue); 
      xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Sheets[SheetName]; 

      xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.ActiveSheet; 

      xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Sheets.get_Item(SheetName); 
      xlWorkSheet.Activate(); 
      // object StartRange = "B"; 
      // object EndRange = misValue; 

      // xlRange = xlWorkSheet.get_Range("A", "M"); 
      // xlRange = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.get_Range(StartRange, misValue); 

      //Header 
      //for (i = 0; i < dt.Columns.Count; i++) 
      //{ 
      // xlRange.Cells[1, i + 1] = dt.Columns[i].ColumnName; 

      //} 
      //Datas 
      for (int i = 0; i < dt.Rows.Count; i++) 
      { 
       for (int j = 0; j < dt.Columns.Count; j++) 
       { 
        xlApp.Cells[i + 13, j + 1] = dt.Rows[i][j].ToString(); 
       } 
      } 
      if (Filepath != null || Filepath != "") 
      { 
       try 
       { 
        xlApp.ActiveWorkbook.SaveAs(Filepath); 
        xlApp.Quit(); 

        xlWorkSheet = null; 
        xlWorkBook = null; 
        xlApp = null; 
       } 
       catch (Exception ex) 
       { 
        throw new Exception("Can not save file" + ex.Message); 
       } 
      } 
      else 
      { 
       xlApp.Visible = true; 
      } 
      return dt; 
     } 
     catch (Exception ex) 
     { 
      throw new Exception(ex.Message); 
     }