如何从C#中的数据集或数据表中导出Excel? [英] How to export excel from dataset or datatable in c#?

查看:79
本文介绍了如何从C#中的数据集或数据表中导出Excel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不使用Gridview的情况下将数据从数据集或数据表导出到C#中的Excel文件中.

I want to export data from Dataset or Data Table to Excel file in C# without using Gridview.

推荐答案

获取更多方法:我有这段代码,但是为此,您需要包括Excel Com Component

I have this code but for this you need to include Excel Com Component

在项目中添加Microsoft.Office.Interop.Excel.dll的引用将为您完成任务.

Add reference of Microsoft.Office.Interop.Excel.dll in your project will do task for you.

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;
}

这篇关于如何从C#中的数据集或数据表中导出Excel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆