Export data from DataTable to Excel file

2019-08-08 03:19发布

I have DataTable object. How can I export it into an XLS file? I tried to render it via DataGrid

DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
dgGrid.RenderControl(hw);

but the file is very large and the OutOfMemoryException appears.

I can use http://epplus.codeplex.com/. I need C# function.

3条回答
狗以群分
2楼-- · 2019-08-08 03:55

First of all, Google is your best friend. Also you can search on this site.

Some solutions:

  • You can write an excel file with SQL.
  • You can use the reference to Microsoft Office library to create an excel file
  • You can write an XML file.
查看更多
Deceive 欺骗
3楼-- · 2019-08-08 04:02

There are a number of options, one of them being the Access OLE DB Provider which also operates in terms of DataTables.

If you want more fine-grained support over the document, I'd recommend the Open XML SDK 2.0, whixh is .xmlx only.

For raw data, I think that Access OLE DB (also reffered to as the ACE provider) is the best choice since it enables a database-like experience. Open XML assumes fairly good knowledge of XML and the willingnes to experiment a bit more. On the other hand, you can apply formatting, add formulas and other advanced features.

查看更多
成全新的幸福
4楼-- · 2019-08-08 04:09

Ok, find a solution here: http://bytesofcode.hubpages.com/hub/Export-DataSet-and-DataTable-to-Excel-2007-in-C

Just download epplus library and call method:

private void GenerateExcel(DataTable dataToExcel, string excelSheetName)
        {
            string fileName = "ByteOfCode";
            string currentDirectorypath = Environment.CurrentDirectory;
            string finalFileNameWithPath = string.Empty;

            fileName = string.Format("{0}_{1}", fileName, DateTime.Now.ToString("dd-MM-yyyy"));
            finalFileNameWithPath = string.Format("{0}\\{1}.xlsx", currentDirectorypath, fileName);

            //Delete existing file with same file name.
            if (File.Exists(finalFileNameWithPath))
                File.Delete(finalFileNameWithPath);

            var newFile = new FileInfo(finalFileNameWithPath);

            //Step 1 : Create object of ExcelPackage class and pass file path to constructor.
            using (var package = new ExcelPackage(newFile))
            {
                //Step 2 : Add a new worksheet to ExcelPackage object and give a suitable name
                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(excelSheetName);

                //Step 3 : Start loading datatable form A1 cell of worksheet.
                worksheet.Cells["A1"].LoadFromDataTable(dataToExcel, true, TableStyles.None);

                //Step 4 : (Optional) Set the file properties like title, author and subject
                package.Workbook.Properties.Title = @"This code is part of tutorials available at http://bytesofcode.hubpages.com";
                package.Workbook.Properties.Author = "Bytes Of Code";
                package.Workbook.Properties.Subject = @"Register here for more http://hubpages.com/_bytes/user/new/";

                //Step 5 : Save all changes to ExcelPackage object which will create Excel 2007 file.
                package.Save();

                MessageBox.Show(string.Format("File name '{0}' generated successfully.", fileName)
                    , "File generated successfully!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
查看更多
登录 后发表回答