将数据从DataTable移动到Excel时出现异常

时间:2013-03-11 13:31:04

标签: c# excel xlsx

在以下代码中,被注释的语句抛出异常

try {
    foreach(DataRow dr in dt.Rows) {
        for(int i=1; i<NumColumns+1; i++) {

            // this statement throws 
            xlWorkSheet.Cells[rowCount, i].value=dr[i - 1].ToString();

        }
        rowCount+=1;
    }

}
catch(Exception) {
    throw;
}

它试图移动的数据如下:

  

=== 3 ===

以下是截图:

UdScI.png

这可以解决吗?或者我是否需要使用其他工具进行研究以将数据移动到Excel中(例如closedXML)?

2 个答案:

答案 0 :(得分:2)

这是因为字符串以等号开头,因此会产生公式。您可以使用撇号然后等号(即以'=开头)。

您的原始字符串可能会导致COMException HRESULT:0x800A03EC显示以下屏幕截图:

43uKH.jpg

使用我测试的以下代码,对

等数据没有任何问题
  

'=== 3 ===

代码:

namespace TestNamespace {
    using Excel=Microsoft.Office.Interop.Excel;

    public static class TestClass {
        static DataTable BuildTestDataTable() {
            var dt=new DataTable();
            dt.Columns.Add("Name", typeof(String));
            dt.Columns.Add("Age", typeof(int));
            dt.Columns.Add("Gender", typeof(String));
            dt.Columns.Add("Memo", typeof(String));

            dt.Rows.Add(new object[] { "Leon Scott Kennedy", 36, "M", "'=== 1 ===" });
            dt.Rows.Add(new object[] { "Ada Wong", 39, "F", "'=== 3 ===" });
            return dt;
        }

        public static void ExportToExcel(this DataTable dt, String fileName) {
            var xlApp=new Excel.ApplicationClass();

            var xlWorkBook=xlApp.Workbooks.Open(
                fileName,
                0,
                false, // for read/write
                5, "", "", true, Excel.XlPlatform.xlWindows,
                "\t", false, false, 0, true, 1, 0
                );

            var xlWorkSheet=(Excel.Worksheet)xlWorkBook.Worksheets[1];
            var NumColumns=dt.Columns.Count;
            var rowCount=dt.Rows.Count;

            try {
                foreach(DataRow dr in dt.Rows) {
                    for(int i=1; i<NumColumns+1; i++) {
                        xlWorkSheet.Cells[rowCount, i]=dr[i-1].ToString();
                    }
                    rowCount+=1;
                }

                xlWorkBook.Save();
            }
            catch(Exception) {
                throw;
            }
            finally {
                xlApp.Quit();
            }
        }

        public static void TestMethod() {
            TestClass.BuildTestDataTable().ExportToExcel(@"c:\ExistingFile.xlsx");
            // TestClass.BuildTestDataTable().ExportToExcel(@"c:\ExistingFile.xls");
        }
    }
}

答案 1 :(得分:2)

试试这个。

public void ExporttoExcel(DataTable table,string type)
    {

        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.Buffer = true;
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        //HttpContext.Current.Response.ContentType = "application/ms-word";
        HttpContext.Current.Response.Write(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");

        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename="+ type +".xls");
       // HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=Reports.doc");
        HttpContext.Current.Response.Charset = "utf-8";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
        HttpContext.Current.Response.Write("<font style='font-size:10.0pt; font-family:Calibri;'>");
        HttpContext.Current.Response.Write("<BR><BR><BR>");
        HttpContext.Current.Response.Write("<Table border='1' bgColor='#ffffff' borderColor='#000000' cellSpacing='2' cellPadding='2' style='font-size:10.0pt; font-family:Arial; background:white;'> <TR>");
        int columnscount = table.Columns.Count;

        for (int j = 0; j < columnscount; j++)
        {
            HttpContext.Current.Response.Write("<Td>");
            HttpContext.Current.Response.Write("<B>");
            HttpContext.Current.Response.Write(table.Columns[j].ColumnName.ToString());
            HttpContext.Current.Response.Write("</B>");
            HttpContext.Current.Response.Write("</Td>");
        }
        HttpContext.Current.Response.Write("</TR>");
        foreach (DataRow row in table.Rows)
        {
            HttpContext.Current.Response.Write("<TR>");
            for (int i = 0; i < table.Columns.Count; i++)
            {
                HttpContext.Current.Response.Write("<Td>");
                HttpContext.Current.Response.Write(row[i].ToString());
                HttpContext.Current.Response.Write("</Td>");
            }

            HttpContext.Current.Response.Write("</TR>");
        }
        HttpContext.Current.Response.Write("</Table>");
        HttpContext.Current.Response.Write("</font>");
        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.End();
    }