1)如何将Excel写入内存流.2)如何从浏览器下载Excel文件.使用 Micosoft.Office.Interop

本文关键字:Excel 文件 下载 使用 Office Interop 浏览器 Micosoft 内存 | 更新日期: 2023-09-27 18:20:14

//i'm using VS 2008, dll as Microsoft.Office.Interop.Excel
//sample code..
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;                
xlApp = new Excel.ApplicationClass();                
xlWorkBook = xlApp.Workbooks.Add(misValue);//create new work book
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//CREATING ONE Rectangle shape
xlWorkSheet.Shapes.AddShape(MsoAutoShapeType.msoShapeRectangle, 47, 24, 500, 90);
 Microsoft.Office.Interop.Excel.Shape[] myShapes = new Microsoft.Office.Interop.Excel.Shape[1];
 //adding textbox
 myShapes[0] = xlWorkSheet.Shapes.AddTextbox(MsoTextOrientation.msoTextOrientationHorizontal, 75, 60, 70, 30);
myShapes[0].TextFrame.Characters(misValue, misValue).Text = "Tracking";

从浏览器下载选项。

context.Response.ContentType = "application/vnd.ms-excel";
context.Response.AddHeader("Content-Disposition", "attachment; filename= report.xls");

这里我使用的是临时文本文件,但我需要使用临时文件。

string file = context.Server.MapPath("new.txt");
 Byte[] myByte = File.ReadAllBytes(file);
  context.Response.Clear();
  context.Response.BinaryWrite(myByte);
  context.Response.Flush();
  context.Response.Close();

我们可以使用 Ipersiststream 接口将对象保存在内存流中吗?

http://www.eggheadcafe.com/community/csharp/2/10101323/how-to-implement-ipersiststream-interface-in-c.aspx

1)如何将Excel写入内存流.2)如何从浏览器下载Excel文件.使用 Micosoft.Office.Interop

如果您有兴趣创建格式比 GridView 更多的 Excel 文档,您可能需要查看 EPPlus:

http://epplus.codeplex.com/

该库能够创建具有自定义单元格、格式等功能的 Excel 文件。

如果 GridView 适合您,请选择它,但如果不是,则还有其他 Excel 选项。您应该能够将内容保存到内存流并将内存流输出到浏览器。

这是我与 MVC 一起使用 ASP.NET FileResult 处理程序的示例。这个概念可以应用于WebForms,它所做的只是写出到响应流。我的类有一个用于加载数据表的属性(this.dataTable(和您希望浏览器将文件下载为(文件名(和工作簿名称(this.workBookName(的文件名

    protected override void WriteFile(HttpResponseBase response)
    {
        using (ExcelPackage pck = new ExcelPackage())
        {
            ExcelWorksheet ws = pck.Workbook.Worksheets.Add(this.workBookName);
            ws.Cells["A1"].LoadFromDataTable(this.dataTable, true);
            response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            response.AddHeader("content-disposition", "attachment;  filename=" + fileName);
            response.BinaryWrite(pck.GetAsByteArray());
        }
    }

我完全同意约翰·桑德斯的观点,也许你应该尝试这种方式。

将数据集绑定到 GridView,然后将其下载到 Excel。

使用以下代码段从控件获取值

private static void PrepareControlForExport(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            Control current = control.Controls[i];
            if (current is LinkButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
            }
            else if (current is ImageButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
            }
            else if (current is HyperLink)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
            }
            else if (current is DropDownList)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
            }
            else if (current is CheckBox)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
            }
            if (current.HasControls())
            {
                PrepareControlForExport(current);
            }
        }
    }

现在创建一个将从网格视图下载数据的方法。

private void ExportX()
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; Filename = ExcelReport.xls"));
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        StringWriter stringWrite = new StringWriter();
        HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWrite);
        Table table = new Table();
        //  include the gridline settings
        table.GridLines = GridView1.GridLines;
        if (GridView1.HeaderRow != null)
        {
            PrepareControlForExport(GridView1.HeaderRow);
            table.Rows.Add(GridView1.HeaderRow);
        }
        foreach (GridViewRow row in GridView1.Rows)
        {
            PrepareControlForExport(row);
            table.Rows.Add(row);
        }
        if (GridView1.FooterRow != null)
        {
            PrepareControlForExport(GridView1.HeaderRow);
            table.Rows.Add(GridView1.FooterRow);
        }
        table.RenderControl(htmlWriter);
        Response.Write(stringWrite.ToString());
        Response.End();
    }

public override void VerifyRenderingInServerForm(Control control)
    {
    }

这就是您需要做的,调用上述方法下载数据。