2012-08-03 44 views

回答

2

好了,在這裏找到一個解決方案:http://bytesofcode.hubpages.com/hub/Export-DataSet-and-DataTable-to-Excel-2007-in-C

只需下載epplus庫和調用方法:

private void GenerateExcel(DataTable dataToExcel, string excelSheetName) 
     { 
      string fileName = "ByteOfCode"; 
      string currentDirectorypath = Environment.CurrentDirectory; 
      string finalFileNameWithPath = string.Empty; 

      fileName = string.Format("{0}_{1}", fileName, DateTime.Now.ToString("dd-MM-yyyy")); 
      finalFileNameWithPath = string.Format("{0}\\{1}.xlsx", currentDirectorypath, fileName); 

      //Delete existing file with same file name. 
      if (File.Exists(finalFileNameWithPath)) 
       File.Delete(finalFileNameWithPath); 

      var newFile = new FileInfo(finalFileNameWithPath); 

      //Step 1 : Create object of ExcelPackage class and pass file path to constructor. 
      using (var package = new ExcelPackage(newFile)) 
      { 
       //Step 2 : Add a new worksheet to ExcelPackage object and give a suitable name 
       ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(excelSheetName); 

       //Step 3 : Start loading datatable form A1 cell of worksheet. 
       worksheet.Cells["A1"].LoadFromDataTable(dataToExcel, true, TableStyles.None); 

       //Step 4 : (Optional) Set the file properties like title, author and subject 
       package.Workbook.Properties.Title = @"This code is part of tutorials available at http://bytesofcode.hubpages.com"; 
       package.Workbook.Properties.Author = "Bytes Of Code"; 
       package.Workbook.Properties.Subject = @"Register here for more http://hubpages.com/_bytes/user/new/"; 

       //Step 5 : Save all changes to ExcelPackage object which will create Excel 2007 file. 
       package.Save(); 

       MessageBox.Show(string.Format("File name '{0}' generated successfully.", fileName) 
        , "File generated successfully!", MessageBoxButtons.OK, MessageBoxIcon.Information); 
      } 
     } 
1

首先,Google是你最好的朋友。你也可以在這個網站上搜索。

一些解決方案:

  • 你可以寫與SQL的Excel文件。
  • 您可以使用對Microsoft Office庫的引用來創建Excel文件
  • 您可以編寫一個XML文件。
+2

我知道谷歌是我最好的朋友,但我沒有找到解決方案是如何做到這一點正好,所以我在這裏發帖的問題 – ihorko 2012-08-03 14:19:40

2

有很多選項,其中之一是Access OLE DB Provider,其中也運行DataTables。

如果您希望對文檔提供更精細的支持,我建議您使用Open XML SDK 2.0,只有.xmlx。

對於原始數據,我認爲訪問OLE DB(也被認爲是ACE提供者)是最好的選擇,因爲它可以實現類似數據庫的體驗。 Open XML假設了XML的相當好的知識並且願意嘗試更多。另一方面,您可以應用格式,添加公式和其他高級功能。

+0

謝謝,但你的評論它不能解決我的問題 – ihorko 2012-08-03 14:19:16

+0

也許嘗試使你的問題更具體,它不清楚你在找什麼。比我們將能夠更有效地幫助你。 – 2012-08-03 14:22:09