通过XLS操作提高性能

时间:2010-10-11 21:07:50

标签: optimization c#-4.0 performance xls

我有使用字符串将DataTable导出到XLS的简单方法。列数为5 - 30,数字或行可能是1到1000.有时性能有问题,我可以提供建议,我可以在代码中更改。我正在使用.net 4.0

public string FormatCell(string columnName, object value)
        {
        StringBuilder builder = new StringBuilder();
        string formattedValue = string.Empty;
        string type = "String";
        string style = "s21";

        if (!(value is DBNull) && columnName.Contains("GIS"))
            formattedValue = Convert.ToDouble(value).ToString("##.00000000°");
        else if (value is DateTime)
        {
            style = "s22";
            type = "DateTime";
            DateTime date = (DateTime)value;
            formattedValue = date.ToString("yyyy-MM-ddTHH:mm:ss.fff");
        }
        else if (value is double || value is float || value is decimal)
        {
            formattedValue = Convert.ToDecimal(value).ToString("#.00").Replace(',', '.');
            type = "Number";
        }
        else if (value is int)
        {
            formattedValue = value.ToString();
            type = "Number";
        }
        else
            formattedValue = value.ToString();

        builder.Append(string.Format("<Cell ss:StyleID=\"{0}\"><Data ss:Type=\"{1}\">", style, type));

        builder.Append(formattedValue);
        builder.AppendLine("</Data></Cell>");

        return builder.ToString();
    }

    public string ConvertToXls(DataTable table)
    {
        StringBuilder builder = new StringBuilder();

        int rows = table.Rows.Count + 1;
        int cols = table.Columns.Count;

        builder.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
        builder.AppendLine("<?mso-application progid=\"Excel.Sheet\"?>");
        builder.AppendLine("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"");
        builder.AppendLine(" xmlns:o=\"urn:schemas-microsoft-com:office:office\"");
        builder.AppendLine(" xmlns:x=\"urn:schemas-microsoft-com:office:excel\"");
        builder.AppendLine(" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"");
        builder.AppendLine(" xmlns:html=\"http://www.w3.org/TR/REC-html40/\">");
        builder.AppendLine(" <DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">;");
        builder.AppendLine("  <Author>Author</Author>");
        builder.AppendLine(string.Format("  <Created>{0}T{1}Z</Created>", DateTime.Now.ToString("yyyy-mm-dd"), DateTime.Now.ToString("HH:MM:SS")));
        builder.AppendLine("  <Company>Company</Company>");
        builder.AppendLine("  <Version>1.0</Version>");
        builder.AppendLine(" </DocumentProperties>");
        builder.AppendLine(" <ExcelWorkbook xmlns=\"urn:schemas-microsoft-com:office:excel\">");
        builder.AppendLine("  <WindowHeight>8955</WindowHeight>");
        builder.AppendLine("  <WindowWidth>11355</WindowWidth>");
        builder.AppendLine("  <WindowTopX>480</WindowTopX>");
        builder.AppendLine("  <WindowTopY>15</WindowTopY>");
        builder.AppendLine("  <ProtectStructure>False</ProtectStructure>");
        builder.AppendLine("  <ProtectWindows>False</ProtectWindows>");
        builder.AppendLine(" </ExcelWorkbook>");
        builder.AppendLine(" <Styles>");
        builder.AppendLine("  <Style ss:ID=\"Default\" ss:Name=\"Normal\">");
        builder.AppendLine("   <Alignment ss:Vertical=\"Bottom\"/>");
        builder.AppendLine("   <Borders/>");
        builder.AppendLine("   <Font/>");
        builder.AppendLine("   <Interior/>");
        builder.AppendLine("   <Protection/>");
        builder.AppendLine("  </Style>");
        builder.AppendLine("  <Style ss:ID=\"s21\">");
        builder.AppendLine("   <Alignment ss:Vertical=\"Bottom\" ss:WrapText=\"1\"/>");
        builder.AppendLine("  </Style>");
        builder.AppendLine("  <Style ss:ID=\"s22\">");
        builder.AppendLine("    <NumberFormat ss:Format=\"Short Date\"/>");
        builder.AppendLine("  </Style>");
        builder.AppendLine(" </Styles>");
        builder.AppendLine(" <Worksheet ss:Name=\"Export\">");
        builder.AppendLine(string.Format("  <Table ss:ExpandedColumnCount=\"{0}\" ss:ExpandedRowCount=\"{1}\" x:FullColumns=\"1\"", cols.ToString(), rows.ToString()));
        builder.AppendLine("   x:FullRows=\"1\">");

        //generate title
        builder.AppendLine("<Row>");
        foreach (DataColumn eachColumn in table.Columns)  // you can write a half columns of table and put the remaining columns in sheet2
        {
            if (eachColumn.ColumnName != "ID")
            {
                builder.Append("<Cell ss:StyleID=\"s21\"><Data ss:Type=\"String\">");
                builder.Append(eachColumn.ColumnName.ToString());
                builder.AppendLine("</Data></Cell>");
            }
        }
        builder.AppendLine("</Row>");

        //generate data
        foreach (DataRow eachRow in table.Rows)
        {
            builder.AppendLine("<Row>");
            foreach (DataColumn eachColumn in table.Columns)
            {
                if (eachColumn.ColumnName != "ID")
                {
                    builder.AppendLine(FormatCell(eachColumn.ColumnName, eachRow[eachColumn]));
                }
            }
            builder.AppendLine("</Row>");
        }
        builder.AppendLine("  </Table>");
        builder.AppendLine("  <WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">");
        builder.AppendLine("   <Selected/>");
        builder.AppendLine("   <Panes>");
        builder.AppendLine("    <Pane>");
        builder.AppendLine("     <Number>3</Number>");
        builder.AppendLine("     <ActiveRow>1</ActiveRow>");
        builder.AppendLine("    </Pane>");
        builder.AppendLine("   </Panes>");
        builder.AppendLine("   <ProtectObjects>False</ProtectObjects>");
        builder.AppendLine("   <ProtectScenarios>False</ProtectScenarios>");
        builder.AppendLine("  </WorksheetOptions>");
        builder.AppendLine(" </Worksheet>");
        builder.AppendLine(" <Worksheet ss:Name=\"Sheet2\">");
        builder.AppendLine("  <WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">");
        builder.AppendLine("   <ProtectObjects>False</ProtectObjects>");
        builder.AppendLine("   <ProtectScenarios>False</ProtectScenarios>");
        builder.AppendLine("  </WorksheetOptions>");
        builder.AppendLine(" </Worksheet>");
        builder.AppendLine(" <Worksheet ss:Name=\"Sheet3\">");
        builder.AppendLine("  <WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">");
        builder.AppendLine("   <ProtectObjects>False</ProtectObjects>");
        builder.AppendLine("   <ProtectScenarios>False</ProtectScenarios>");
        builder.AppendLine("  </WorksheetOptions>");
        builder.AppendLine(" </Worksheet>");
        builder.AppendLine("</Workbook>");

        return builder.ToString();
    }

使用:

string xlsData= ConvertToXls(someTable)


System.CodeDom.Compiler.TempFileCollection fileCollection = new System.CodeDom.Compiler.TempFileCollection();

                    string tempFileName = fileCollection.AddExtension("xls", true);

                    if (File.Exists(tempFileName))
                        File.Delete(tempFileName);

                    using (StreamWriter writer = new StreamWriter(tempFileName, false, Encoding.UTF8))
                        writer.Write(xlsData);

4 个答案:

答案 0 :(得分:2)

您可以做的最简单的事情是声明StringBuilder的容量不是默认值,例如

StringBuilder builder = new StringBuilder(100000);

默认分配是16个字节,每次需要重新分配时都会加倍。这意味着如果您使用默认值,它将被重新分配多次。

除非你的系统内存紧张,或者这确实非常庞大,否则我怀疑直接按照之前的建议流式传输它会产生很大的不同。我怀疑它实际上可能会使事情变得更糟,因为我怀疑文件流写入的开销较少而不是将数据添加到已经分配的StreamBuilder对象(假设它不需要经常重新分配!)

最佳解决方案可能是将stringbuilder输出定期发送到流,因为它增长到某个大小(基于系统内存),如果它可能超过10或20兆字节。这样,您可以避免内存问题,并避免与输出流的许多小写相关联的任何潜在开销。

更新 - 测试说明:

我运行了一些测试来创建非常大的字符串(> 50兆字节),并且提前分配内存几乎没有明显差异。

但更重要的是,使用最简单的形式创建这样一个字符串所需的时间量:

  for (int i = 0; i < 10000000; i++)
  {
     builder.AppendLine("a whole bunch of text designed to see how long it takes to build huge strings ");
  }

几乎无关紧要。我可以在几秒钟内填满所有台式电脑的内存。

这意味着StringBuilder的开销根本不是你的问题。人们也可以从中推断,切换到流写入肯定也无法帮助你。

相反,您需要查看一些您正在进行数千次或数万次的操作。这个循环::

foreach (DataRow eachRow in table.Rows)
        {
            builder.AppendLine("<Row>");
            foreach (DataColumn eachColumn in table.Columns)
            {
                if (eachColumn.ColumnName != "ID")
                {
                    builder.AppendLine(FormatCell(eachColumn.ColumnName, eachRow[eachColumn]));
                }
            }
            builder.AppendLine("</Row>");
        }
  • 取消检查 ColumnName!=“ID”删除它 来自您的选择
  • FormatCell为每个数据元素运行一次。对此效率的微小改变可能会产生巨大影响
  • 以前没想过这个,但如果您的DataTable来自SQL数据源,请直接使用DataReader而不是内存中的DataTable

改进FormatCell的建议:

  • 提前构建每列数据类型的索引,这样您每次都不必进行代价高昂的类型比较
  • 设置Type和Style的字符串值,并根据数据类型对其进行更改是很昂贵的。请改用枚举,然后根据枚举值使用硬编码字符串输出值。
  • 将FormatCell中的任何变量移动到主类中,这样就不需要在每次调用过程时创建/分配它们

要构建索引,我认为最有效的方法是将列号映射到定义每列类型的数组,如下面的代码,然后在FormatCell中使用预先构建的columnnumbers映射数据类型。

enum DataTypes
    {
        DateTime = 1,
        Float = 2,
        Int = 3,
        String = 4
    }
    DataTypes[] types = new DataTypes[tbl.Columns.Count];
    for (int col=0;i<tbl.Columns.Count;col++) {
        object value = tbl.Rows[0][col];
        if (value is double || value is float || value is decimal) {
            types[col]=DataTypes.Float;
        } else if (value is DateTime) {
            types[col]=DataTypes.DateTime;
        } else if (value is int) {
            types[col]=DataTypes.Int;
        } else {
            types[col]=DataTypes.String;
        }
    }

然后将FormatCell传递给columnumber,它可以从数组中查找数据类型,只需检查一下开关:

switch(types[colNumber]) {
   case DataTypes.DateTime:
       ...
       break;
   case DataTypes.Int:
...
 /// and so on
}

我认为这会减少很多开销。

答案 1 :(得分:1)

您应该使用dotTrace之类的内容对代码进行分析,以了解时间的变化。至少要在定时器中查看每个部件需要多长时间。在不知道瓶颈所在的情况下进行优化可能是浪费时间。 EG:

   DateTime startTime = DateTime.Now;
   Debug.WriteLine("Start : " + startTime);

   //some code

   Debug.WriteLine("End: " + DateTime.Now);
   Debug.WriteLine("Elapsed : " + (DateTime.Now - startTime));

我认为上面的约翰是正确的。使用流。例如

StreamWriter streamWriter = System.IO.File.CreateText("c:\\mynewfile.xls");

streamWriter.AutoFlush = false;

//lots of writes

streamWriter.Flush();
streamWriter.Close();

您应该使用autoflush false和true进行测试。您可能还想尝试一个内存流。

StreamWriter streamWriter = new StreamWriter(new MemoryStream());

答案 2 :(得分:0)

嗯,你只是在内存中创建一个越来越大的字符串......所以随着大小的增加会变得越来越糟。

有没有什么理由你没有把它传输到文件中,而不是构建一个GIANT字符串,然后将其序列化为文件?

添加详细信息后进行修改:

不是让ConvertToXLS返回一个字符串,而是将该streamwriter传递给convertToXLS方法。

public void ConvertToXLS( DataTable table, StreamWriter stream )
{
    ...
}
<\ n>在ConverToXLS内部,摆脱StringBuilder,并将builder.AppendLine( x )的所有调用替换为

stream.WriteLine(x); 

当你走的时候,你正在写入流而不是创建一个巨大的字符串。

答案 3 :(得分:0)

而不是将行写出两次,一次在内存中然后写入磁盘,尝试将其归结为一次写入操作。直接到磁盘。

我不知道.net中的xml对象和stringbuilder之间的性能比较是什么,但如果我知道我写的是Xml,我倾向于选择xml对象解决方案,xmlwriter xlinq等。知道每次生产符合xml标准的数据非常令人放心。

SS上的其他帖子表示他们认为使用XmlTextWriter比使用StringBuilder更快。

StringBuilder vs XmlTextWriter

关于更改缓冲区大小和延迟写入的答案将起作用,但是可能会非常受欢迎,是的,如果您在内存中完成所有操作会更快,但是您的内存占用可能会变得非常大,因此操作系统可能会进行一些影响整个机器的磁盘交换。(取决于你在机器上运行的内容)。找到快乐的妥协,然后以您的生产系统满意的写入速度流式传输数据。

相关问题