现在的位置: 首页 > 编程语言 > 正文

C#导出Excel的6种简单方法实现

2020年02月13日 编程语言 ⁄ 共 11131字 ⁄ 字号 评论关闭

作者 | Johnson Manohar译者 | 谭开朗,责编 | 黄浩然出品 | CSDN(ID:CSDNnews)

Syncfusion Excel (XlsIO) 库是一个 .Net Excel 库,它支持用户用 C# 和 VB.NET 以一个非常简易的方式,将各种数据源(如数据表,数组,对象集合,数据库,CSV / TSV,和微软网格控件等)数据导出到 Excel 。

将数据导出到 Excel 可以以更容易理解的方式可视化数据。该特性有助于生成财务报告、银行报表和发票,同时还支持筛选大数据、验证数据、格式化数据等。

将数据导出到 Excel, Essential XlsIO 提供了以下方法:

数据表导出到 Excel 对象集合导出到 Excel 数据库导出到 Excel 微软网格控件导出到 Excel 数组导出到 Excel CSV 导出到 Excel

在本文中,我们将研究这些方法以及如何执行它们。

数据表导出到 Excel

ADO.NET 对象的数据(如 datatable 、datacolumn 和 dataview )可以导出到Excel 工作表。通过识别列类型或单元格值类型、超链接和大型数据集,可以在几秒钟内将其导出并作为列标头。

将数据表导出到 Excel 工作表可以通过 ImportDataTable 方法实现。下面的代码示例演示了如何将员工详细信息的数据表导出到 Excel 工作表。

using (ExcelEngine excelEngine = new ExcelEngine()){ IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2016; //Create a new workbook IWorkbook workbook = application.Workbooks.Create(1); IWorksheet sheet = workbook.Worksheets[0]; //Create a dataset from XML file DataSet customersDataSet = new DataSet(); customersDataSet.ReadXml(Path.GetFullPath(@"../../Data/Employees.xml")); //Create datatable from the dataset DataTable dataTable = new DataTable(); dataTable = customersDataSet.Tables[0]; //Import data from the data table with column header, at first row and first column, //and by its column type. sheet.ImportDataTable(dataTable, true, 1, 1, true); //Creating Excel table or list object and apply style to the table IListObject table = sheet.ListObjects.Create("Employee_PersonalDetails", sheet.UsedRange); table.BuiltInTableStyle = TableBuiltInStyles.TableStyleMedium14; //Autofit the columns sheet.UsedRange.AutofitColumns(); //Save the file in the given path Stream excelStream = File.Create(Path.GetFullPath(@"Output.xlsx")); workbook.SaveAs(excelStream); excelStream.Dispose();}

将数据表输出到Excel

在将大数据导出到 Excel 时,如果不需要应用数字格式和样式,可以将其中importOnSave 参数的值设为 TRUE,使用 ImportDataTable 方法重载。此时,导出数据与保存 Excel 文件是同时进行的。

使用此方法导出高性能的大数据。

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

如果你有指定范围,并且希望将数据从指定范围的特定行和列导出到指定范围,那么可以使用下面的 API,其中 rowOffset 和 columnOffset 是要从指定范围中的特定单元导入的参数。

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

对象集合导出到 Excel

将对象集合中的数据导出到 Excel 工作表是常见的场景。但是,如果需要将数据从模板导出到 Excel 工作表,这个方法将非常有用。

Syncfusion Excel (XlsIO) 库支持将对象集合中的数据导出到 Excel 工作表。

我们可以通过 ImportData 方法将对象集合中的数据导出到 Excel 工作表。下面的代码示例演示了如何将数据从集合导出到 Excel 工作表。

using (ExcelEngine excelEngine = new ExcelEngine()){ IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2016; //Read the data from XML file StreamReader reader = new StreamReader(Path.GetFullPath(@"../../Data/Customers.xml")); //Assign the data to the customerObjects collection IEnumerable customerObjects = GetData (reader.ReadToEnd()); //Create a new workbook IWorkbook workbook = application.Workbooks.Create(1); IWorksheet sheet = workbook.Worksheets[0]; //Import data from customerObjects collection sheet.ImportData(customerObjects, 5, 1, false); #region Define Styles IStyle pageHeader = workbook.Styles.Add("PageHeaderStyle"); IStyle tableHeader = workbook.Styles.Add("TableHeaderStyle"); pageHeader.Font.RGBColor = Color.FromArgb(0, 83, 141, 213); pageHeader.Font.FontName = "Calibri"; pageHeader.Font.Size = 18; pageHeader.Font.Bold = true; pageHeader.HorizontalAlignment = ExcelHAlign.HAlignCenter; pageHeader.VerticalAlignment = ExcelVAlign.VAlignCenter; tableHeader.Font.Color = ExcelKnownColors.White; tableHeader.Font.Bold = true; tableHeader.Font.Size = 11; tableHeader.Font.FontName = "Calibri"; tableHeader.HorizontalAlignment = ExcelHAlign.HAlignCenter; tableHeader.VerticalAlignment = ExcelVAlign.VAlignCenter; tableHeader.Color = Color.FromArgb(0, 118, 147, 60); tableHeader.Borders[ExcelBordersIndex.EdgeLeft].LineStyle = ExcelLineStyle.Thin; tableHeader.Borders[ExcelBordersIndex.EdgeRight].LineStyle = ExcelLineStyle.Thin; tableHeader.Borders[ExcelBordersIndex.EdgeTop].LineStyle = ExcelLineStyle.Thin; tableHeader.Borders[ExcelBordersIndex.EdgeBottom].LineStyle = ExcelLineStyle.Thin; #endregion #region Apply Styles //Apply style to the header sheet["A1"].Text = "Yearly Sales Report"; sheet["A1"].CellStyle = pageHeader; sheet["A2"].Text = "Namewise Sales Comparison Report"; sheet["A2"].CellStyle = pageHeader; sheet["A2"].CellStyle.Font.Bold = false; sheet["A2"].CellStyle.Font.Size = 16; sheet["A1:D1"].Merge(); sheet["A2:D2"].Merge(); sheet["A3:A4"].Merge(); sheet["D3:D4"].Merge(); sheet["B3:C3"].Merge(); sheet["B3"].Text = "Sales"; sheet["A3"].Text = "Sales Person"; sheet["B4"].Text = "January - June"; sheet["C4"].Text = "July - December"; sheet["D3"].Text = "Change(%)"; sheet["A3:D4"].CellStyle = tableHeader; sheet.UsedRange.AutofitColumns(); sheet.Columns[0].ColumnWidth = 24; sheet.Columns[1].ColumnWidth = 21; sheet.Columns[2].ColumnWidth = 21; sheet.Columns[3].ColumnWidth = 16; #endregion sheet.UsedRange.AutofitColumns(); //Save the file in the given path Stream excelStream = File.Create(Path.GetFullPath(@"Output.xlsx")); workbook.SaveAs(excelStream); excelStream.Dispose();}

将对象集合输出到Excel

数据库导出到 Excel

Excel 支持从不同的数据库创建 Excel 表。如果你需要使用 Excel 从数据库创建一个或多个 Excel 表,那么需要逐个建立连接来创建。这可能很耗费时间。所以,如果能找到一种从数据库快速、轻松地生成 Excel 表的替代方法,这难道不是首选方法吗?

Syncfusion Excel (XlsIO) 库可以将数据从 MS SQL 、MS Access 、Oracle 等数据库导出到 Excel 工作表。通过在数据库和 Excel 应用程序之间建立连接,可以将数据从数据库导出到 Excel 表。

可以使用 Refresh() 方法更新映射到数据库的 Excel 表中的修改数据。

最重要的是,你可以参考文档从外部连接创建一个表,以了解如何将数据库导出到Excel 表。下面的代码示例演示了如何将数据从数据库导出到 Excel 表。

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

将数据库输出到Excel表

将数据从 DataGrid 、GridView 、DataGridView 导出到 Excel

从微软网格控件导出数据到 Excel 工作表,有助于以不同的方式可视化数据。你可能要花费数小时从网格单元格中遍历其数据及其样式,以便将它们导出到 Excel 工作表。对于那些需要将数据从微软网格控件导出到 Excel 工作表的人来说,这应该是个好消息,因为使用 Syncfusion Excel 库导出要快得多。

Syncfusion Excel (XlsIO) 库支持通过调用一个 API,将来自微软网格控件(如DataGrid 、GridView 和 DataGridView )的数据导出到 Excel 工作表。此外,你还可以使用标题和样式导出数据。

下面的代码示例演示了如何将数据从 DataGridView 导出到 Excel 工作表。

#region Loading the data to DataGridViewDataSet customersDataSet = new DataSet();//Read the XML file with datastring inputXmlPath = Path.GetFullPath(@"../../Data/Employees.xml");customersDataSet.ReadXml(inputXmlPath);DataTable dataTable = new DataTable();//Copy the structure and data of the tabledataTable = customersDataSet.Tables[1].Copy();//Removing unwanted columnsdataTable.Columns.RemoveAt(0);dataTable.Columns.RemoveAt(10);this.dataGridView1.DataSource = dataTable;dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.White;dataGridView1.RowsDefaultCellStyle.BackColor = Color.LightBlue;dataGridView1.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font("Tahoma", 9F, ((System.Drawing.FontStyle)(System.Drawing.FontStyle.Bold)));dataGridView1.ForeColor = Color.Black;dataGridView1.BorderStyle = BorderStyle.None;#endregionusing (ExcelEngine excelEngine = new ExcelEngine()){ IApplication application = excelEngine.Excel; //Create a workbook with single worksheet IWorkbook workbook = application.Workbooks.Create(1); IWorksheet worksheet = workbook.Worksheets[0]; //Import from DataGridView to worksheet worksheet.ImportDataGridView(dataGridView1, 1, 1, isImportHeader: true, isImportStyle: true); worksheet.UsedRange.AutofitColumns(); workbook.SaveAs("Output.xlsx");}

Microsoft DataGridView到Excel

数组导出到 Excel

有时,可能需要将数据数组插入或修改到 Excel 工作表中的现有数据中。在这种情况下,行数和列数是预先知道的。数组在固定范围时非常有用。

Syncfusion Excel (XlsIO) 库支持将数据数组导出到 Excel 工作表中,水平方向和垂直方向导出均可。此外,还可以导出二维数组。

让我们考虑一个场景,“人均开支”。一个人全年的花费都列在 Excel 工作表中。在这个场景中,你需要在新建一行,添加一个新用户 Paul Pogba 的开销,并更新所有被跟踪人员 12 月的开销。

从数组导出前的 Excel 数据

可以通过 ImportArray 方法将数据数组导出到 Excel 工作表。下面的代码示例演示了如何将数据数组导出到 Excel 工作表中,水平方向和垂直方向都是如此。

using (ExcelEngine excelEngine = new ExcelEngine()){ IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2016; //Reads input Excel stream as a workbook IWorkbook workbook = application.Workbooks.Open(File.OpenRead(Path.GetFullPath(@"../../../Expenses.xlsx"))); IWorksheet sheet = workbook.Worksheets[0]; //Preparing first array with different data types object[] expenseArray = new object[14] {"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)"}; //Inserting a new row by formatting as a previous row. sheet.InsertRow(11, 1, ExcelInsertOptions.FormatAsBefore); //Import Peter's expenses and fill it horizontally sheet.ImportArray(expenseArray, 11, 1, false); //Preparing second array with double data type double[] expensesOnDec = new double[6] {179.00d, 298.00d, 484.00d, 145.00d, 20.00d, 497.00d}; //Modify the December month's expenses and import it vertically sheet.ImportArray(expensesOnDec, 6, 13, true); //Save the file in the given path Stream excelStream = File.Create(Path.GetFullPath(@"Output.xlsx")); workbook.SaveAs(excelStream); excelStream.Dispose();}

将数据数组输出到Excel

CSV 导出到 Excel

逗号分隔值 (CSV) 文件有助于生成列数少、行数多的表格数据或轻量级报告。Excel 格式打开这些文件,更容易读懂数据。Syncfusion Excel (XlsIO) 库支持在几秒钟内打开和保存 CSV 文件。下面的代码示例演示了如何打开 CSV 文件,并将其保存为 XLSX 文件。最重要的是,数据显示在数字格式的表格中。

using (ExcelEngine excelEngine = new ExcelEngine()){ IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2016; //Preserve data types as per the value application.PreserveCSVDataTypes = true; //Read the CSV file Stream csvStream = File.OpenRead(Path.GetFullPath(@"../../../TemplateSales.csv")); ; //Reads CSV stream as a workbook IWorkbook workbook = application.Workbooks.Open(csvStream); IWorksheet sheet = workbook.Worksheets[0]; //Formatting the CSV data as a Table IListObject table = sheet.ListObjects.Create("SalesTable", sheet.UsedRange); table.BuiltInTableStyle = TableBuiltInStyles.TableStyleMedium6; IRange location = table.Location; location.AutofitColumns(); //Apply the proper latitude & longitude numerformat in the table TryAndUpdateGeoLocation(table,"Latitude"); TryAndUpdateGeoLocation(table,"Longitude"); //Apply currency numberformat in the table column 'Price' IRange columnRange = GetListObjectColumnRange(table,"Price"); if(columnRange != null) columnRange.CellStyle.NumberFormat = "$#,##0.00"; //Apply Date time numberformat in the table column 'Transaction_date' columnRange = GetListObjectColumnRange(table,"Transaction_date"); if(columnRange != null) columnRange.CellStyle.NumberFormat = "m/d/yy h:mm AM/PM;@"; //Sort the data based on 'Products' IDataSort sorter = table.AutoFilters.DataSorter; ISortField sortField = sorter. SortFields. Add(0, SortOn. Values, OrderBy. Ascending); sorter. Sort(); //Save the file in the given path Stream excelStream; excelStream = File.Create(Path.GetFullPath(@"../../../Output.xlsx")); workbook.SaveAs(excelStream); excelStream.Dispose();}

输入csv文件

csv转换成excel的输出

总结

如你所见, Syncfusion Excel (XlsIO) 库提供了 C# 将数据导出到 Excel 的各种简单方法。我们可以有效地使用它们生成高性能的 Excel 报表或处理大数据。建议花点时间仔细阅读文档,你会发现其他选项和特性,以及所有附带的代码示例。使用该库,还可以将 Excel 数据导出为 PDF、图像、数据表、CSV、TSV、HTML、对象集合、ODS文件格式等。

原文:https://www.syncfusion.com/blogs/post/6-easy-ways-to-export-data-to-excel-in-c-sharp.aspx

本文为CSDN翻译,转载请注明来源出处。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

本文标题: C# 导出Excel的6种简单方法实现

以上就上有关C#导出Excel的6种简单方法实现的全部内容,学步园全面介绍编程技术、操作系统、数据库、web前端技术等内容。

抱歉!评论已关闭.