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

发布于 2024-12-26 07:16:58 字数 1612 浏览 1 评论 0原文

//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

//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";

//download option from browser.

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

//here i'm using temporary text file.but i need without using temporary file..

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

Can we use Ipersiststream interface to save the objects in memorystream ?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷血 2025-01-02 07:16:59

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

http://epplus.codeplex.com/

该库能够创建 Excel 文件,并能够自定义单元格、格式等。

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

下面是我在 ASP.NET MVC 中使用的 FileResult 处理程序的示例。这个概念可以应用于WebForms,它所做的只是写出到响应流。我的类有一个用于加载数据表的属性 (this.dataTable) 以及您希望浏览器下载文件的文件名 (fileName) 和工作簿名称 (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());

        }
    }

If you have an interest in creating an Excel document with more formatting than the GridView can do you may want to take a look at EPPlus:

http://epplus.codeplex.com/

The library is capable of creating Excel files with the ability to customize cells, formats, etc.

If the GridView works for you, go for it, but if not there are other Excel options. You should be able to save the content to a memory stream and output the memory stream to the browser.

Here is a sample of a FileResult handeler that I've used with ASP.NET MVC. The concept can be applied to WebForms, all it does is write out to the response stream. My class has a property for the datatable to load (this.dataTable) and the file name you want the browser to download the file as (fileName) and the work book name (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());

        }
    }
唐婉 2025-01-02 07:16:59

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

将数据集绑定到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);
            }
        }
    }

现在创建一个将从 gridview 下载数据的方法。

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)
    {

    }

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

I am completely agree with John Saunders, may be you should try this way.

Bind the dataset to GridView and then download it to excel.

Use below segment of code to get the value from the control

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

Now Create a method which will download the data from gridview.

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)
    {

    }

That's all you need to do, call the above method to download the data.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文