【问题标题】:Appending data from database to Excel in Asp.Net在 Asp.Net 中将数据从数据库附加到 Excel
【发布时间】:2014-09-11 08:24:11
【问题描述】:

我开发了一个应用程序,我必须将数据从数据库插入 Excel,插入数据的大小是预定义的。

假设任何城市有 20 条记录。现在首先我只需要插入 5 条记录,然后在查看给用户的一些消息后,接下来 5 条数据将附加到同一个 Excel 文件中,依此类推。

以下是我将数据插入 Excel 的代码,大小在 Web.Config 文件中定义。

Web.Config 代码:

<appSettings>
  <add key="UserRecord" value="6"/>
</appSettings>

代码:

public void InsertRecordToExcel()
    {
        DAL ObjDal = new DAL();
        string record = ConfigurationManager.AppSettings["UserRecord"];
        try
        {
            int n = Convert.ToInt32(record);
            string filename = Server.MapPath("UserDataSheet");
            string City = TxtCityName.Text;
            DataTable dt = new DataTable();
            dt = ObjDal.GetData(City);
            while(dt.Rows.Count>0)
            {
                StringWriter writer = new StringWriter();
                HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);
                GridView gridView = new GridView();
                DataTable dtn = new DataTable();
                gridView.DataSource = dt.AsEnumerable().Take(n).CopyToDataTable();
                gridView.AutoGenerateColumns = true;
                gridView.DataBind();
                gridView.RenderControl(htmlWriter);
                htmlWriter.Close();
                Response.Clear();
                Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".xls");
                Response.Charset = "";
                Response.Write(writer.ToString());
                Response.End();
                LblMessage.Text = n + " " + "Record Added Successfully";
            }                
        }

        catch (Exception ex)
        {
            throw ex;
        }
    }

将数据附加到 Excel 文件的过程是什么?

【问题讨论】:

  • 您不能附加到您已经发送给用户的 excel 文件中,他们已经下载了它。你甚至没有这样做,你只是向他们发送 HTML,打开时 Excel 会变成电子表格。
  • 如果我删除下载代码呢? @BenRobinson
  • @BenRobinson 有没有办法做到这一点?请为我提供一些代码..
  • 我不是来给你写代码的,我不太明白你需要什么。
  • 我只是想在 excel 中插入一些大小的数据,并在再次提供消息后将其余数据附加到 excel 中。 @BenRobinson

标签: c# asp.net excel


【解决方案1】:

例如,您可以使用 xmlwriter 创建 excel 文件。或者更舒适的方法是为此使用库。 (Create Excel (.XLS and .XLSX) file from C#)

与图书馆:

    void export_Click(object sender, EventArgs e){
        byte[] data = File.ReadAllBytes("export.xls"); //The created excel file with the library, if the library supports getting the excel as a stream you can use the method below to stream it.
        string filename = "export.xls"; 

        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename="+filename);
        Response.AddHeader("Content-Type", "application/Excel");
        Response.ContentType = "application/vnd.xls";
        Response.AddHeader("Content-Length", bytesInStream.Length.ToString());
        Response.BinaryWrite(data);
        Response.End();       
    }

xml的方式:

     void export_Click(object sender, EventArgs e){
        MemoryStream ms = ExportDataTableToWorksheet(ds, ds2, true);
        byte[] bytesInStream = ms.ToArray(); 

        string filename = "export.xls";

        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename="+filename);
        Response.AddHeader("Content-Type", "application/Excel");
        Response.ContentType = "application/vnd.xls";
        Response.AddHeader("Content-Length", bytesInStream.Length.ToString());
        Response.BinaryWrite(bytesInStream);
        Response.End();       
    }

    public static MemoryStream ExportDataTableToWorksheet(DataSet ds)
    {
        MemoryStream ms = new MemoryStream();
        XmlTextWriter writer = new XmlTextWriter(ms, Encoding.UTF8);

        writer.Formatting = Formatting.Indented;

        // <?xml version="1.0"?>
        writer.WriteStartDocument();

        // <?mso-application progid="Excel.Sheet"?>
        writer.WriteProcessingInstruction("mso-application", "progid=\"Excel.Sheet\"");

        // <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet >"
        writer.WriteStartElement("Workbook", "urn:schemas-microsoft-com:office:spreadsheet");

        // Namespace definitions
        writer.WriteAttributeString("xmlns", "o", null, "urn:schemas-microsoft-com:office:office");
        writer.WriteAttributeString("xmlns", "x", null, "urn:schemas-microsoft-com:office:excel");
        writer.WriteAttributeString("xmlns", "ss", null, "urn:schemas-microsoft-com:office:spreadsheet");
        writer.WriteAttributeString("xmlns", "html", null, "http://www.w3.org/TR/REC-html40");

        // <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
        writer.WriteStartElement("DocumentProperties", "urn:schemas-microsoft-com:office:office");

        // Documentattributes Author, Date, Company
        writer.WriteElementString("Author", Environment.UserName);
        writer.WriteElementString("LastAuthor", Environment.UserName);
        writer.WriteElementString("Created", DateTime.Now.ToString("u") + "Z");
        writer.WriteElementString("Company", "Unknown");
        writer.WriteElementString("Version", "11.8122");

        // </DocumentProperties>
        writer.WriteEndElement();

        // <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
        writer.WriteStartElement("ExcelWorkbook", "urn:schemas-microsoft-com:office:excel");

        // Workbook-Preferences
        writer.WriteElementString("WindowHeight", "13170");
        writer.WriteElementString("WindowWidth", "17580");
        writer.WriteElementString("WindowTopX", "120");
        writer.WriteElementString("WindowTopY", "60");
        writer.WriteElementString("ProtectStructure", "False");
        writer.WriteElementString("ProtectWindows", "False");

        // </ExcelWorkbook>
        writer.WriteEndElement();

        // <Styles>
        writer.WriteStartElement("Styles");

        // <Style ss:ID="Default" ss:Name="Normal">
        writer.WriteStartElement("Style");
        writer.WriteAttributeString("ss", "ID", null, "Default");
        writer.WriteAttributeString("ss", "Name", null, "Normal");

        // <Alignment ss:Vertical="Bottom"/>
        writer.WriteStartElement("Alignment");
        writer.WriteAttributeString("ss", "Vertical", null, "Bottom");
        writer.WriteEndElement();

        // Verbleibende Sytle-Eigenschaften leer schreiben
        writer.WriteElementString("Borders", null);
        writer.WriteElementString("Font", null);
        writer.WriteElementString("Interior", null);
        writer.WriteElementString("NumberFormat", null);
        writer.WriteElementString("Protection", null);

        // </Style>
        writer.WriteEndElement();

        // </Styles>
        writer.WriteEndElement();

        // <Worksheet ss:Name="xxx">
        writer.WriteStartElement("Worksheet");
        writer.WriteAttributeString("ss", "Name", null, "export");

        // <Table ss:ExpandedColumnCount="2" ss:ExpandedRowCount="3" x:FullColumns="1" x:FullRows="1" ss:DefaultColumnWidth="60">
        writer.WriteStartElement("Table");

        // setting the column count
        writer.WriteAttributeString("ss", "ExpandedColumnCount", null, "1");
        else writer.WriteAttributeString("ss", "ExpandedRowCount", null, (ds.Tables[0].Rows.Count).ToString());
        writer.WriteAttributeString("x", "FullColumns", null, "1");
        writer.WriteAttributeString("x", "FullRows", null, "1");
        writer.WriteAttributeString("ss", "DefaultColumnWidth", null, "100");

        foreach (DataRow row in ds.Tables[0].Rows)
        {
            // <Row>
            writer.WriteStartElement("Row");

            // Alle Zellen der aktuellen Zeile durchlaufen

            writeCell(writer, (string)row["name"]);

            // </Row>
            writer.WriteEndElement();
        }
        // </Table>
        writer.WriteEndElement();

        // <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
        writer.WriteStartElement("WorksheetOptions", "urn:schemas-microsoft-com:office:excel");

        // pagesetup
        writer.WriteStartElement("PageSetup");
        writer.WriteStartElement("Header");
        writer.WriteAttributeString("x", "Margin", null, "0.4921259845");
        writer.WriteEndElement();
        writer.WriteStartElement("Footer");
        writer.WriteAttributeString("x", "Margin", null, "0.4921259845");
        writer.WriteEndElement();
        writer.WriteStartElement("PageMargins");
        writer.WriteAttributeString("x", "Bottom", null, "0.984251969");
        writer.WriteAttributeString("x", "Left", null, "0.78740157499999996");
        writer.WriteAttributeString("x", "Right", null, "0.78740157499999996");
        writer.WriteAttributeString("x", "Top", null, "0.984251969");
        writer.WriteEndElement();
        writer.WriteEndElement();

        // <Selected/>
        writer.WriteElementString("Selected", null);

        // <Panes>
        writer.WriteStartElement("Panes");

        // <Pane>
        writer.WriteStartElement("Pane");

        //
        writer.WriteElementString("Number", "1");
        writer.WriteElementString("ActiveRow", "1");
        writer.WriteElementString("ActiveCol", "1");

        // </Pane>
        writer.WriteEndElement();

        // </Panes>
        writer.WriteEndElement();

        // <ProtectObjects>False</ProtectObjects>
        writer.WriteElementString("ProtectObjects", "False");

        // <ProtectScenarios>False</ProtectScenarios>
        writer.WriteElementString("ProtectScenarios", "False");

        // </WorksheetOptions>
        writer.WriteEndElement();

        // </Worksheet>
        writer.WriteEndElement();

        // </Workbook>
        writer.WriteEndElement();

        writer.Flush();
        writer.Close();
        return ms;
    }

    /// <summary>
    /// Removes control characters and other non-UTF-8 characters
    /// </summary>
    /// <param name="inString">The string to process</param>
    /// <returns>A string with no control characters or entities above 0x00FD</returns>
    public static string RemoveTroublesomeCharacters(string input)
    {
        var isValid = new Predicate<char>(value =>
    (value >= 0x0020 && value <= 0xD7FF) ||
    (value >= 0xE000 && value <= 0xFFFD) ||
    value == 0x0009 ||
    value == 0x000A ||
    value == 0x000D);

        return new string(Array.FindAll(input.ToCharArray(), isValid));

    }

    static void writeCell(XmlTextWriter writer, string value)
    {
        // <Cell>
        writer.WriteStartElement("Cell");

        // <Data ss:Type="String">xxx</Data>
        writer.WriteStartElement("Data");
        writer.WriteAttributeString("ss", "Type", null, "String");

        // Zelleninhakt schreiben
        writer.WriteValue(value);

        // </Data>
        writer.WriteEndElement();

        // </Cell>
        writer.WriteEndElement();
    }

【讨论】:

  • 感谢您的代码。我在哪里可以定义记录的大小?
  • writer.WriteAttributeString("ss", "ExpandedColumnCount", null, "1"); writer.WriteAttributeString("ss", "ExpandedRowCount",..) 在这里定义需要多少列和行。也许您可以轻松地从数据表中获取大小
【解决方案2】:

“在查看给用户的一些消息后” - 这是什么消息,你在哪里显示这个? 假设此消息在网络/桌面上,只需将前 5 条记录插入到 excel 中,维护 excel 工作簿实例,显示消息,将下一组数据插入到活动工作簿中。

另一个想法是使用数据表,只有当用户下载 excel 时,你才会填写 excel

如果你能解释显示消息的意义会很有帮助

【讨论】:

  • 假设用户想要显示某个城市的记录,当用户点击提交按钮时,该消息将显示在标签上
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多