【问题标题】:How to save created excel file to Client pc in ASP.NET如何在 ASP.NET 中将创建的 Excel 文件保存到客户端 PC
【发布时间】:2012-06-11 05:40:27
【问题描述】:

当我单击按钮时,我在 asp.net 中创建了一个 excel 报告和 html 报告,我的应用程序创建它并保存到客户端桌面,但是它不能正常工作,因为 excel 文件是在服务器的桌面中创建的。我该如何解决这个问题?

感谢您的回复。

string CurrentDate;
DateTime saveNow = DateTime.Now;
CurrentDate = saveNow.Date.ToShortDateString();
string reportContent = prepareHTM();

string pathFile = Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory) + "\\As_Build_Report_ "+ CurrentDate + ".html";

using (StreamWriter outfile = new StreamWriter(pathFile, true))
{
    outfile.WriteLine(reportContent);
}
System.Diagnostics.Process.Start(pathFile);

object missing = System.Reflection.Missing.Value;
//Start Excel Application.
Excel.Application oXL = new Excel.Application();
oXL.Visible = true; //display Application .            
Excel._Workbook oWB = (Excel._Workbook)(oXL.Workbooks.Add(missing));//create a new workbook.
Excel._Worksheet oSheet = (Excel._Worksheet)oWB.ActiveSheet; //create a sheet                

string CurrentDate;
DateTime saveNow = DateTime.Now;
CurrentDate = saveNow.Date.ToString();
int keep = 5;
string project = list[0].Project;
oSheet.Cells[1, 3] = "MiKES Configuration Management __" + project + "__ As-Built Report";
oSheet.Cells[3, 1] = "Report Date :";
oSheet.Cells[3, 2] = CurrentDate;

oSheet.Cells[keep, 1] = "PART NO";
oSheet.Cells[keep, 2] = "REF.DES.";
oSheet.Cells[keep, 3] = "DESCRIPTION";
oSheet.Cells[keep, 4] = "SERIAL NO";
oSheet.Cells[keep, 5] = "C/S";
oSheet.Cells[keep, 6] = "D/C";
oSheet.Cells[keep, 7] = "REMARK";
keep++;
foreach(Classes.CMNewPart item in list)
{
    try
    {
        oSheet.Cells[keep, 1] = item.PartNo;
        oSheet.Cells[keep, 2] = item.RefDes;
        oSheet.Cells[keep, 3] = item.Description1;
        oSheet.Cells[keep, 4] = item.SerialNo;
        oSheet.Cells[keep, 5] = item.Cs;
        oSheet.Cells[keep, 6] = item.Dc;
        oSheet.Cells[keep, 7] = item.Remark;
    }
    catch (Exception)
    {

    }
    keep++;
}

【问题讨论】:

  • 顺便说一句,如果您从服务器运行它,您应该真正考虑使用 OpenXML SDK(或其他解决方案)来生成文件,而不是互操作。为什么要让 Excel 可见?

标签: c# asp.net


【解决方案1】:

您需要使用 Response 对象将文件发送给客户端。忽略客户端打开 excel 文件时的警告消息 -

为防止这种情况,您需要在响应中提及内容类型和长度 使用示例代码

//Read the Excel file in a byte array. here pck is the Excelworkbook              
Byte[] fileBytes = pck.GetAsByteArray();

//Clear the response               
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Cookies.Clear();
//Add the header & other information      
Response.Cache.SetCacheability(HttpCacheability.Private);
Response.CacheControl = "private";
Response.Charset = System.Text.UTF8Encoding.UTF8.WebName;
Response.ContentEncoding = System.Text.UTF8Encoding.UTF8;
Response.AppendHeader("Content-Length", fileBytes.Length.ToString());
Response.AppendHeader("Pragma", "cache");
Response.AppendHeader("Expires", "60");
Response.AppendHeader("Content-Disposition",
"attachment; " +
"filename=\"ExcelReport.xlsx\"; " +
"size=" + fileBytes.Length.ToString() + "; " +
"creation-date=" + DateTime.Now.ToString("R") + "; " +
"modification-date=" + DateTime.Now.ToString("R") + "; " +
"read-date=" + DateTime.Now.ToString("R"));
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
//Write it back to the client    
Response.BinaryWrite(fileBytes);
Response.End();

【讨论】:

  • 不适合我。它以图像数据/base64 格式返回我的 excel 文件,并在 Chrome 中为我提供 err_response_headers_multiple_content_disposition。从 iFrame 调用此方法。 $("#iframe").attr("src", "/Pages/JourneyPlan.aspx?download=true&fileName=" + data.d);
  • 不知道为什么人们投反对票。这个解决方案在几年前就奏效了。浏览器和 Excel 都已更新,可能无法按预期工作。
【解决方案2】:

你可以写excel文件来回复HttpResponse.WriteFile Method

string CurrentDate;
DateTime saveNow = DateTime.Now;
CurrentDate = saveNow.Date.ToShortDateString();
string reportContent = prepareHTM();

string pathFile = Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory) + "\\As_Build_Report_ "+ CurrentDate + ".html";

using (StreamWriter outfile = new StreamWriter(pathFile, true))
{
    outfile.WriteLine(reportContent);
}

System.IO.FileInfo file = new System.IO.FileInfo(pathFile); 
Response.Clear(); 
Response.Charset="UTF-8"; 
Response.ContentEncoding=System.Text.Encoding.UTF8; 
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); 
Response.AddHeader("Content-Length", file.Length.ToString());    
Response.ContentType = "application/ms-excel";  
Response.WriteFile(file.FullName); 
Response.End(); 

【讨论】:

  • 这个服务器端代码对我有用。我在客户端使用 iframe 来调用。 $("#iframe").attr("src", "/Pages/JourneyPlan.aspx?download=true&fileName=" + data. d);
【解决方案3】:

要注意一件重要的事情,以便选择的最佳答案适合您:
您必须使用与问题中暗示的 Microsoft.Office.Interop.Excel 不同的库。您必须使用 EPPlus。这是您在项目中设置它的方式:

  1. 在 Visual Studio 的包管理器控制台中,键入:Install-Package EPPlus(这将根据需要安装库和参考)
  2. 添加这个 using 语句 (using OfficeOpenXml;)

这是一些示例代码,用于创建最佳答案中提到的 excel 包 (pck):

    ExcelPackage pck = new ExcelPackage();
    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("exported data");
    // Excel sheet headings
    ws.Cells[1, 1].Value = "Column 1 title";
    ws.Cells[1, 2].Value = "Column 2 title";


现在您可以使用最佳答案中提供的代码了。

【讨论】:

    【解决方案4】:

    您不能直接将其保存到特定的客户端位置。您可以做的是返回带有该请求的文件,以便在浏览器端弹出“保存文件”对话框。

    【讨论】:

    • 我该怎么做你能给我更多的信息或简单的代码。谢谢
    • 我正在使用移动设备。今天晚些时候会这样做。
    猜你喜欢
    • 2011-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 2016-08-04
    • 1970-01-01
    相关资源
    最近更新 更多