项目作者: SyncfusionExamples

项目描述 :
This repository contains Syncfusion Excel library examples that explain how to export data to Excel in C#, from the data table, collection of objects, database, Microsoft Grid controls, array, and CSV. This works without Microsoft Excel Interop.
高级语言: C#
项目地址: git://github.com/SyncfusionExamples/export-data-to-excel-in-c-sharp.git


Export Data to Excel in C

Syncfusion® Excel (XlsIO) library is a .NET Excel library that allows the user to export data to Excel in C# and VB.NET from various data sources like data tables, arrays, collections of objects, databases, CSV/TSV, and Microsoft Grid controls in a very simple and easy way. Exporting data to Excel helps in visualizing the data in a more understandable fashion. This feature helps to generate financial reports, banking statements, and invoices, while also allowing for filtering large data, validating data, formatting data, and more.

You can refer the documention to know more in detail.

Essential® XlsIO provides the following ways to export data to Excel:

  1. DataTable to Excel
  2. Collection of objects to Excel
  3. Database to Excel
  4. Microsoft Grid controls to Excel
  5. Array to Excel
  6. CSV to Excel

This repository contains the examples of these methods and explains how to implement them.

1. Export from DataTable to Excel

Data from ADO.NET objects such as datatable, datacolumn, and dataview can be exported to Excel worksheets. The exporting can be done as column headers, by recognizing column types or cell value types, as hyperlinks, and as large dataset, all in a few seconds.

Exporting DataTable to Excel worksheets can be achieved through the ImportDataTable method. The following code sample shows how to export a datatable of employee details to an Excel worksheet.

  1. using (ExcelEngine excelEngine = new ExcelEngine())
  2. {
  3. IApplication application = excelEngine.Excel;
  4. application.DefaultVersion = ExcelVersion.Excel2016;
  5. //Preserve data types as per the value
  6. application.PreserveCSVDataTypes = true;
  7. //Read the CSV file
  8. Stream csvStream = File.OpenRead(Path.GetFullPath(@"../../../TemplateSales.csv")); ;
  9. //Reads CSV stream as a workbook
  10. IWorkbook workbook = application.Workbooks.Open(csvStream);
  11. IWorksheet sheet = workbook.Worksheets[0];
  12. //Formatting the CSV data as a Table
  13. IListObject table = sheet.ListObjects.Create("SalesTable", sheet.UsedRange);
  14. table.BuiltInTableStyle = TableBuiltInStyles.TableStyleMedium6;
  15. IRange location = table.Location;
  16. location.AutofitColumns();
  17. //Apply the proper latitude & longitude numerformat in the table
  18. TryAndUpdateGeoLocation(table,"Latitude");
  19. TryAndUpdateGeoLocation(table,"Longitude");
  20. //Apply currency numberformat in the table column 'Price'
  21. IRange columnRange = GetListObjectColumnRange(table,"Price");
  22. if(columnRange != null)
  23. columnRange.CellStyle.NumberFormat = "$#,##0.00";
  24. //Apply Date time numberformat in the table column 'Transaction_date'
  25. columnRange = GetListObjectColumnRange(table,"Transaction_date");
  26. if(columnRange != null)
  27. columnRange.CellStyle.NumberFormat = "m/d/yy h:mm AM/PM;@";
  28. //Sort the data based on 'Products'
  29. IDataSort sorter = table.AutoFilters.DataSorter;
  30. ISortField sortField = sorter. SortFields. Add(0, SortOn. Values, OrderBy. Ascending);
  31. sorter. Sort();
  32. //Save the file in the given path
  33. Stream excelStream;
  34. excelStream = File.Create(Path.GetFullPath(@"../../../Output.xlsx"));
  35. workbook.SaveAs(excelStream);
  36. excelStream.Dispose();
  37. }

Export DataTable to Excel in C#

Output of DataTable to Excel

When exporting large data to Excel, and if there is no need to apply number formats and styles, you can make use of the ImportDataTable overload with the TRUE value for importOnSave parameter. Here, the export happens while saving the Excel file.

Use this option to export large data with high performance.

  1. value = instance.ImportDataTable(dataTable, firstRow, firstColumn, importOnSave)

If you have a named range and like to export data to a named range from a specific row and column of the named range, you can make use of the below API, where rowOffset and columnOffset are the parameters to import from a particular cell in a named range.

  1. value = instance.ImportDataTable(dataTable, namedRange, showColumnName, rowOffset, colOffset);

2. Export from collection of objects to Excel

Exporting data from a collection of objects to an Excel worksheet is a common scenario. However, this option will be helpful if you need to export data from a model to an Excel worksheet.

The Syncfusion® Excel (XlsIO) library provides support to export data from a collection of objects to an Excel worksheet.

Exporting data from a collection of objects to an Excel worksheet can be achieved through the ImportData method. The following code example shows how to export data from a collection to an Excel worksheet.

  1. using (ExcelEngine excelEngine = new ExcelEngine())
  2. {
  3. IApplication application = excelEngine.Excel;
  4. application.DefaultVersion = ExcelVersion.Excel2016;
  5. //Read the data from XML file
  6. StreamReader reader = new StreamReader(Path.GetFullPath(@"../../Data/Customers.xml"));
  7. //Assign the data to the customerObjects collection
  8. IEnumerable customerObjects = GetData (reader.ReadToEnd());
  9. //Create a new workbook
  10. IWorkbook workbook = application.Workbooks.Create(1);
  11. IWorksheet sheet = workbook.Worksheets[0];
  12. //Import data from customerObjects collection
  13. sheet.ImportData(customerObjects, 5, 1, false);
  14. #region Define Styles
  15. IStyle pageHeader = workbook.Styles.Add("PageHeaderStyle");
  16. IStyle tableHeader = workbook.Styles.Add("TableHeaderStyle");
  17. pageHeader.Font.RGBColor = Color.FromArgb(0, 83, 141, 213);
  18. pageHeader.Font.FontName = "Calibri";
  19. pageHeader.Font.Size = 18;
  20. pageHeader.Font.Bold = true;
  21. pageHeader.HorizontalAlignment = ExcelHAlign.HAlignCenter;
  22. pageHeader.VerticalAlignment = ExcelVAlign.VAlignCenter;
  23. tableHeader.Font.Color = ExcelKnownColors.White;
  24. tableHeader.Font.Bold = true;
  25. tableHeader.Font.Size = 11;
  26. tableHeader.Font.FontName = "Calibri";
  27. tableHeader.HorizontalAlignment = ExcelHAlign.HAlignCenter;
  28. tableHeader.VerticalAlignment = ExcelVAlign.VAlignCenter;
  29. tableHeader.Color = Color.FromArgb(0, 118, 147, 60);
  30. tableHeader.Borders[ExcelBordersIndex.EdgeLeft].LineStyle = ExcelLineStyle.Thin;
  31. tableHeader.Borders[ExcelBordersIndex.EdgeRight].LineStyle = ExcelLineStyle.Thin;
  32. tableHeader.Borders[ExcelBordersIndex.EdgeTop].LineStyle = ExcelLineStyle.Thin;
  33. tableHeader.Borders[ExcelBordersIndex.EdgeBottom].LineStyle = ExcelLineStyle.Thin;
  34. #endregion
  35. #region Apply Styles
  36. //Apply style to the header
  37. sheet["A1"].Text = "Yearly Sales Report";
  38. sheet["A1"].CellStyle = pageHeader;
  39. sheet["A2"].Text = "Namewise Sales Comparison Report";
  40. sheet["A2"].CellStyle = pageHeader;
  41. sheet["A2"].CellStyle.Font.Bold = false;
  42. sheet["A2"].CellStyle.Font.Size = 16;
  43. sheet["A1:D1"].Merge();
  44. sheet["A2:D2"].Merge();
  45. sheet["A3:A4"].Merge();
  46. sheet["D3:D4"].Merge();
  47. sheet["B3:C3"].Merge();
  48. sheet["B3"].Text = "Sales";
  49. sheet["A3"].Text = "Sales Person";
  50. sheet["B4"].Text = "January - June";
  51. sheet["C4"].Text = "July - December";
  52. sheet["D3"].Text = "Change(%)";
  53. sheet["A3:D4"].CellStyle = tableHeader;
  54. sheet.UsedRange.AutofitColumns();
  55. sheet.Columns[0].ColumnWidth = 24;
  56. sheet.Columns[1].ColumnWidth = 21;
  57. sheet.Columns[2].ColumnWidth = 21;
  58. sheet.Columns[3].ColumnWidth = 16;
  59. #endregion
  60. sheet.UsedRange.AutofitColumns();
  61. //Save the file in the given path
  62. Stream excelStream = File.Create(Path.GetFullPath(@"Output.xlsx"));
  63. workbook.SaveAs(excelStream);
  64. excelStream.Dispose();
  65. }

Export collection of objects to Excel in c#

Output of collection of objects to Excel

3. Export from Database to Excel

Excel supports creating Excel tables from different databases. If you have a scenario in which you need to create one or more Excel tables from a database using Excel, you need to establish every single connection to create those tables. This can be time consuming, so if you find an alternate way to generate Excel tables from database very quickly and easily, wouldn’t that be your first choice?

The Syncfusion® Excel (XlsIO) library helps you to export data to Excel worksheets from databases like MS SQL, MS Access, Oracle, and more. By establishing a connection between the databases and Excel application, you can export data from a database to an Excel table.

You can use the Refresh() option to update the modified data in the Excel table that is mapped to the database.

Above all, you can refer to the documentation to create a table from an external connection to learn more about how to export databases to Excel tables. The following code sample shows how to export data from a database to an Excel table.

  1. using (ExcelEngine excelEngine = new ExcelEngine())
  2. {
  3. IApplication application = excelEngine.Excel;
  4. application.DefaultVersion = ExcelVersion.Excel2016;
  5. //Create a new workbook
  6. IWorkbook workbook = application.Workbooks.Create(1);
  7. IWorksheet sheet = workbook.Worksheets[0];
  8. if(sheet.ListObjects.Count == 0)
  9. {
  10. //Estabilishing the connection in the worksheet
  11. string dBPath = Path.GetFullPath(@"../../Data/EmployeeData.mdb");
  12. string ConnectionString = "OLEDB;Provider=Microsoft.JET.OLEDB.4.0;Password=\"\";User ID=Admin;Data Source="+ dBPath;
  13. string query = "SELECT EmployeeID,FirstName,LastName,Title,HireDate,Extension,ReportsTo FROM [Employees]";
  14. IConnection Connection = workbook.Connections.Add("Connection1", "Sample connection with MsAccess", ConnectionString, query, ExcelCommandType.Sql);
  15. sheet.ListObjects.AddEx(ExcelListObjectSourceType.SrcQuery, Connection, sheet.Range["A1"]);
  16. }
  17. //Refresh Excel table to get updated values from database
  18. sheet.ListObjects[0].Refresh();
  19. sheet.UsedRange.AutofitColumns();
  20. //Save the file in the given path
  21. Stream excelStream = File.Create(Path.GetFullPath(@"Output.xlsx"));
  22. workbook.SaveAs(excelStream);
  23. excelStream.Dispose();
  24. }

Export Database to Excel in c#

Output of Database to Excel table

4. Export data from DataGrid, GridView, DatGridView to Excel

Exporting data from Microsoft grid controls to Excel worksheets helps to visualize data in different ways. You may work for hours to iterate data and its styles from grid cells to export them into Excel worksheets. It should be good news for those who export data from Microsoft grid controls to Excel worksheets, because exporting with Syncfusion® Excel library is much faster.

Syncfusion® Excel (XlsIO) library supports to exporting data from Microsoft Grid controls, such as DataGrid, GridView, and DataGridView to Excel worksheets in a single API call. Also, you can export data with header and styles.

The following code example shows how to export data from DataGridView to an Excel worksheet.

  1. #region Loading the data to DataGridView
  2. DataSet customersDataSet = new DataSet();
  3. //Read the XML file with data
  4. string inputXmlPath = Path.GetFullPath(@"../../Data/Employees.xml");
  5. customersDataSet.ReadXml(inputXmlPath);
  6. DataTable dataTable = new DataTable();
  7. //Copy the structure and data of the table
  8. dataTable = customersDataSet.Tables[1].Copy();
  9. //Removing unwanted columns
  10. dataTable.Columns.RemoveAt(0);
  11. dataTable.Columns.RemoveAt(10);
  12. this.dataGridView1.DataSource = dataTable;
  13. dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.White;
  14. dataGridView1.RowsDefaultCellStyle.BackColor = Color.LightBlue;
  15. dataGridView1.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font("Tahoma", 9F, ((System.Drawing.FontStyle)(System.Drawing.FontStyle.Bold)));
  16. dataGridView1.ForeColor = Color.Black;
  17. dataGridView1.BorderStyle = BorderStyle.None;
  18. #endregion
  19. using (ExcelEngine excelEngine = new ExcelEngine())
  20. {
  21. IApplication application = excelEngine.Excel;
  22. //Create a workbook with single worksheet
  23. IWorkbook workbook = application.Workbooks.Create(1);
  24. IWorksheet worksheet = workbook.Worksheets[0];
  25. //Import from DataGridView to worksheet
  26. worksheet.ImportDataGridView(dataGridView1, 1, 1, isImportHeader: true, isImportStyle: true);
  27. worksheet.UsedRange.AutofitColumns();
  28. workbook.SaveAs("Output.xlsx");
  29. }

Export Microsoft DataGridView to Excel in c#

Microsoft DataGridView to Excel

5. Export from array to Excel

Sometimes, there may be a need where an array of data may need to be inserted or modified into existing data in Excel worksheet. In this case, the number of rows and columns are known in advance. Arrays are useful when you have a fixed size.

The Syncfusion® Excel (XlsIO) library provides support to export an array of data into an Excel worksheet, both horizontally and vertically. In addition, two-dimensional arrays can also be exported.

Let us consider a scenario, “Expenses per Person.” The expenses of a person for the whole year is tabulated in the Excel worksheet. In this scenario, you need to add expenses for a new person, Paul Pogba, in a new row and modify the expenses of all tracked people for the month Dec.

Excel data before exporting from array to Excel in c#

Excel data before exporting from array

Exporting an array of data to Excel worksheet can be achieved through the ImportArray method. The following code sample shows how to export an array of data to an Excel worksheet, both horizontally and vertically.

  1. using (ExcelEngine excelEngine = new ExcelEngine())
  2. {
  3. IApplication application = excelEngine.Excel;
  4. application.DefaultVersion = ExcelVersion.Excel2016;
  5. //Reads input Excel stream as a workbook
  6. IWorkbook workbook = application.Workbooks.Open(File.OpenRead(Path.GetFullPath(@"../../../Expenses.xlsx")));
  7. IWorksheet sheet = workbook.Worksheets[0];
  8. //Preparing first array with different data types
  9. object[] expenseArray = new object[14]
  10. {"Paul Pogba", 469.00d, 263.00d, 131.00d, 139.00d, 474.00d, 253.00d, 467.00d, 142.00d, 417.00d, 324.00d, 328.00d, 497.00d, "=SUM(B11:M11)"};
  11. //Inserting a new row by formatting as a previous row.
  12. sheet.InsertRow(11, 1, ExcelInsertOptions.FormatAsBefore);
  13. //Import Peter's expenses and fill it horizontally
  14. sheet.ImportArray(expenseArray, 11, 1, false);
  15. //Preparing second array with double data type
  16. double[] expensesOnDec = new double[6]
  17. {179.00d, 298.00d, 484.00d, 145.00d, 20.00d, 497.00d};
  18. //Modify the December month's expenses and import it vertically
  19. sheet.ImportArray(expensesOnDec, 6, 13, true);
  20. //Save the file in the given path
  21. Stream excelStream = File.Create(Path.GetFullPath(@"Output.xlsx"));
  22. workbook.SaveAs(excelStream);
  23. excelStream.Dispose();
  24. }

Export array of data to Excel in c#

Output of array of data to Excel

6. Export from CSV to Excel

Comma-separated value (CSV) files are helpful in generating tabular data or lightweight reports with few columns and a high number of rows. Excel opens such files to make the data easier to read.

The Syncfusion® Excel (XlsIO) library supports opening and saving CSV files in seconds. The below code example shows how to open a CSV file, also save it as XLSX file. Above all, the data is shown in a table with number formats applied.

  1. using (ExcelEngine excelEngine = new ExcelEngine())
  2. {
  3. IApplication application = excelEngine.Excel;
  4. application.DefaultVersion = ExcelVersion.Excel2016;
  5. //Preserve data types as per the value
  6. application.PreserveCSVDataTypes = true;
  7. //Read the CSV file
  8. Stream csvStream = File.OpenRead(Path.GetFullPath(@"../../../TemplateSales.csv")); ;
  9. //Reads CSV stream as a workbook
  10. IWorkbook workbook = application.Workbooks.Open(csvStream);
  11. IWorksheet sheet = workbook.Worksheets[0];
  12. //Formatting the CSV data as a Table
  13. IListObject table = sheet.ListObjects.Create("SalesTable", sheet.UsedRange);
  14. table.BuiltInTableStyle = TableBuiltInStyles.TableStyleMedium6;
  15. IRange location = table.Location;
  16. location.AutofitColumns();
  17. //Apply the proper latitude & longitude numerformat in the table
  18. TryAndUpdateGeoLocation(table,"Latitude");
  19. TryAndUpdateGeoLocation(table,"Longitude");
  20. //Apply currency numberformat in the table column 'Price'
  21. IRange columnRange = GetListObjectColumnRange(table,"Price");
  22. if(columnRange != null)
  23. columnRange.CellStyle.NumberFormat = "$#,##0.00";
  24. //Apply Date time numberformat in the table column 'Transaction_date'
  25. columnRange = GetListObjectColumnRange(table,"Transaction_date");
  26. if(columnRange != null)
  27. columnRange.CellStyle.NumberFormat = "m/d/yy h:mm AM/PM;@";
  28. //Sort the data based on 'Products'
  29. IDataSort sorter = table.AutoFilters.DataSorter;
  30. ISortField sortField = sorter. SortFields. Add(0, SortOn. Values, OrderBy. Ascending);
  31. sorter. Sort();
  32. //Save the file in the given path
  33. Stream excelStream;
  34. excelStream = File.Create(Path.GetFullPath(@"../../../Output.xlsx"));
  35. workbook.SaveAs(excelStream);
  36. excelStream.Dispose();
  37. }

Input CSV File

Input CSV file

Export CSV to Excel in c#

Output of CSV converted to Excel

Apart from this, Syncfusion® Excel (XlsIO) library provides various other features such as, charts, pivot tables, tables, cell formatting, conditional formatting, data validation, encryption and decryption, auto-shapes, Excel to PDF, Excel to Image, Excel to HTML and more. You can refer to our online demo samples to know more about all the features.