0

我有一个 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;
}

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

代码是从这里的stackoverflow页面粘贴的

4

1 回答 1

2

这里根据msdn ,Missing.Value是在System.Reflection. 您应该添加对此命名空间的引用。

using System.Reflection;
于 2013-01-03T10:08:57.917 回答