2013-03-01 34 views
1

我正在處理從我的gridview生成動態excel文件的c#項目。默認情況下,我如何生成類型爲'文本'而不是'常規'的Excel文件

,當我成功生成是將所有的數據到Genaral類型的文件,但我需要所有的excel文件數據到Text格式,

我怎麼能這樣做?當我需要進一步使用該文件報告的目的和需要Text類型

以下是我的Excel文件生成的C#代碼:

private void ExportGridView() 
     { 
      System.IO.StringWriter sw = new System.IO.StringWriter(); 
      System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw); 

      // Render grid view control. 
      gvFiles.RenderControl(htw); 

      // Write the rendered content to a file. 
      string renderedGridView = sw.ToString(); 
      File.WriteAllText(@"C:\test\ExportedFile.xls", renderedGridView); 
     } 

enter image description here

我想我需要使用Microsoft.Office.Interop.Excel和我可以指定類型也喜歡生成Text

此外,我搜索像我們可以生成它像一個像HTML包含,並使其出類拔萃。

任何人都可以幫助我嗎?

+1

如果你想使用'Microsoft.Office.Interop.Excel',你需要在機器上安裝MS Office。這可以嗎? – 2013-03-01 13:32:19

+0

是的,這對我來說很好,任何人都可以請幫我 – Neo 2013-03-01 13:36:06

回答

4

您可以使用Microsoft.Office.Interop.Excel。添加對其的引用,並在其他使用語句旁邊添加以下using語句。

using Microsoft.Office.Interop.Excel; 

修改ExportGridView方法:

private void ExportGridView() 
{ 
    var path = @"C:\test\ExportedFile.xls"; 
    System.IO.StringWriter sw = new System.IO.StringWriter(); 
    System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw); 

    // Render grid view control. 
    gvFiles.RenderControl(htw); 

    // Write the rendered content to a file. 
    string renderedGridView = sw.ToString(); 
    File.WriteAllText(path, renderedGridView); 
    UpdateFormat(path); 
} 

添加以下方法:

private void UpdateFormat(string path) 
{ 
    var application = new Microsoft.Office.Interop.Excel.Application(); 
    var doc = application.Workbooks.Open(path); 
    for (int i = 1; i <= doc.Worksheets.Count; i++) 
    { 
     Worksheet sheet = doc.Worksheets[i]; 
     for (int j = 1; j <= sheet.Columns.Count; j++) 
     { 
      Range column = sheet.Columns[j]; 
      column.NumberFormat = "@"; 
     } 
    } 
    doc.Save(); 
    doc.Close(); 
    application.Quit(); 
} 
+0

謝謝@Alex它適用於我:) – Neo 2013-03-01 17:41:50

+0

但爲什麼它也生成一些'.css','.xml','.htm'文件呢? 我不需要那些,我怎樣才能防止生成這些? – Neo 2013-03-01 17:45:28

0

只是一個猜測,但它是因爲你正在編寫gridview html?您可以創建一個CSV文件並將其保存爲.xls,這將是一個Excel文檔。

+0

我認爲我需要使用'Microsoft.Office.Interop.Excel',我可以指定類型也喜歡在'文本'中生成 任何人都可以幫助我嗎? – Neo 2013-03-01 13:31:19

+1

請注意,簡單地將文件擴展名從CSV更改爲XLS將在某些版本的Excel中打開該文件時生成警告,指出該文件在說明其類型。這不是一個showstopper,但仍然不是很好。 – 2013-03-01 14:59:01

+0

@AlexPaven啊,我之前沒有遇到過這個問題,但它很有意思。謝謝! – 2013-03-01 15:00:40

相關問題