如何在默认情况下生成types为“文本”而不​​是“常规”的Excel文件

我正在从我的GridView生成dynamic的Excel文件的C#项目。

当我成功地生成文件,它将所有的数据转换成Genaraltypes,但我需要把所有的Excel文件数据转换成Text格式,

我怎样才能做到这一点? 由于我需要进一步使用此文件进行报告,并且需要将Text作为types

以下是我的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); } 

在这里输入图像说明

我想我需要使用Microsoft.Office.Interop.Excel ,我可以指定types也喜欢在Text生成

此外,我search就像我们可以生成它像一个像HTML包含,并使其出类拔萃。

谁能帮我?

您可以使用Microsoft.Office.Interop.Excel 。 添加对其的引用,并在其他使用语句旁边添加以下使用语句。

 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(); } 

只是一个猜测,但它是因为你正在写的GridView的HTML? 你可以创build一个CSV文件并用.xls保存,这将是一个excel文档