我正在使用RenderControl
将Excel格式导出为Excel。下面的方法是代码的一部分。
gridExcel.HeaderRow.BackColor = System.Drawing.Color.FromArgb(0, 255, 255, 204);
gridExcel.HeaderRow.Font.Bold = false;
gridExcel.HeaderRow.Height = Unit.Pixel(30);
StringWriter sw = new StringWriter();
gridExcel.RenderControl(new HtmlTextWriter(sw));
string renderedGridView = sw.ToString();
//filename will be like xyz.xls
System.IO.File.WriteAllText(@filename, renderedGridView);
它成功创建了excel文档但是当这个文档从网站下载并且用户从下载文件夹打开它时,每次s \他得到下面提到的错误但用户都能打开文档。
任何人都可以建议可以采取哪些措施来避免这个问题。
答案 0 :(得分:1)
<强>原因强>
此类导出的Excel文件只能用于显示目的,您不能将其用于通常可在有效Excel文件中执行的Excel操作。
摘自here
<强>解强>
您应该使用CLOSEXML来解决它。
public static void ExportToExcel(IEnumerable<dynamic> data, string sheetName)
{
/****** YOUR ORIGINAL CODE *******/
gridExcel.HeaderRow.BackColor = System.Drawing.Color.FromArgb(0, 255, 255, 204);
gridExcel.HeaderRow.Font.Bold = false;
gridExcel.HeaderRow.Height = Unit.Pixel(30);
StringWriter sw = new StringWriter();
gridExcel.RenderControl(new HtmlTextWriter(sw));
string renderedGridView = sw.ToString();
//filename will be like xyz.xls
System.IO.File.WriteAllText(@filename, renderedGridView);
/**************** Set it accordingly by below reference ****************************/
XLWorkbook wb = new XLWorkbook();
var ws = wb.Worksheets.Add(sheetName);
ws.Cell(2, 1).InsertTable(data);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("content-disposition", String.Format(@"attachment;filename={0}.xlsx", sheetName.Replace(" ", "_")));
using (MemoryStream memoryStream = new MemoryStream())
{
wb.SaveAs(memoryStream);
memoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
memoryStream.Close();
}
HttpContext.Current.Response.End();
}
代码参考来自HERE
答案 1 :(得分:0)
您可以尝试这种方法
gridExcel.HeaderRow.BackColor = System.Drawing.Color.FromArgb(0, 255, 255, 204);
gridExcel.HeaderRow.Font.Bold = false;
gridExcel.HeaderRow.Height = Unit.Pixel(30);
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename="@filename+".xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
gridExcel.RenderControl(new HtmlTextWriter(sw));
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();