【问题标题】:Save DataTable data in Excel file asp.Net在 Excel 文件 asp.Net 中保存 DataTable 数据
【发布时间】:2013-01-03 18:08:57
【问题描述】:

我有一个 Gridview,我用数据表填充。在网页上,用户必须能够下载包含 Gridview 内容的 excel 文件。所以 mi 认为保存文件的最简单方法是将数据表保存为 excel 文件。我已经使用了这个方法,我在 stackoverflow 上找到了这个方法。

using Excel = Microsoft.Office.Interop.Excel;
 public static bool ExportDataTableToExcel(DataTable dt, string filepath)
    {

    Excel.Application oXL;
    Excel.Workbook oWB;
    Excel.Worksheet oSheet;
    Excel.Range oRange;

    try
    {
        // Start Excel and get Application object. 
        oXL = new Excel.Application();

        // Set some properties 
        oXL.Visible = true;
        oXL.DisplayAlerts = false;

        // Get a new workbook. 
        oWB = oXL.Workbooks.Add(Missing.Value);

        // Get the Active sheet 
        oSheet = (Excel.Worksheet)oWB.ActiveSheet;
        oSheet.Name = "Data";

        int rowCount = 1;
        foreach (DataRow dr in dt.Rows)
        {
            rowCount += 1;
            for (int i = 1; i < dt.Columns.Count + 1; i++)
            {
                // Add the header the first time through 
                if (rowCount == 2)
                {
                    oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
                }
                oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
            }
        }

        // Resize the columns 
        oRange = oSheet.get_Range(oSheet.Cells[1, 1],
                      oSheet.Cells[rowCount, dt.Columns.Count]);
        oRange.EntireColumn.AutoFit();

        // Save the sheet and close 
        oSheet = null;
        oRange = null;
        oWB.SaveAs(filepath, Excel.XlFileFormat.xlWorkbookNormal,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            Excel.XlSaveAsAccessMode.xlExclusive,
            Missing.Value, Missing.Value, Missing.Value,
            Missing.Value, Missing.Value);
        oWB.Close(Missing.Value, Missing.Value, Missing.Value);
        oWB = null;
        oXL.Quit();
    }
    catch
    {
        throw;
    }
    finally
    {
        // Clean up 
        // NOTE: When in release mode, this does the trick 
        GC.WaitForPendingFinalizers();
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
    }

    return true;
}

但我收到一个构建错误,指出“名称 Missing 在当前上下文中不存在”,我似乎无法弄清楚为什么?谁能帮忙?

代码是从这个stackoverflow页面here粘贴的

【问题讨论】:

  • 你能告诉我们这个异常发生在哪一行吗?
  • 这是一个构建错误。所以它不会跳出异常。但是变量 Missing 带有下划线且未定义。 Cyber​​maxs 的回答是正确的。

标签: c# asp.net .net


【解决方案1】:

根据msdnhereMissing.Value定义在System.Reflection中。您应该添加对此命名空间的引用。

using System.Reflection;

【讨论】:

  • 这成功了。但现在我不断收到这个错误“'object'不包含'get_Range'的定义”我试图设置范围,我也尝试过这样做stackoverflow.com/questions/6546785/…但我仍然无法保存文件。你有什么想法吗?
  • 是的,我得出了这个结论。但我似乎无法弄清楚该怎么做
  • 替换 get_Range 中的 () 并使用带 [] 括号的 Range。
猜你喜欢
  • 1970-01-01
  • 2012-02-23
  • 2011-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多