首页 > 编程语言 >C# 导出Excel的6种简单方法实现

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

时间:2023-09-02 12:22:17浏览次数:41  
标签:sheet C# Excel 导出 table workbook new

 

 更新时间:2019年09月04日 10:11:10   作者:Johnson Manohar     C# 导出 Excel 的6种简单方法:数据表导出到 Excel,对象集合导出到 Excel,数据库导出到 Excel,微软网格控件导出到 Excel,数组导出到 Excel,CSV 导出到 Excel,你都会了吗?需要的朋友们下面随着小编来一起学习学习吧  

作者 | 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 工作表。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 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 文件是同时进行的。

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

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

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

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

对象集合导出到 Excel

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

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

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 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 表。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 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 工作表。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 #region Loading the data to DataGridView DataSet customersDataSet = new DataSet();   //Read the XML file with data string inputXmlPath = Path.GetFullPath(@"../../Data/Employees.xml"); customersDataSet.ReadXml(inputXmlPath); DataTable dataTable = new DataTable();   //Copy the structure and data of the table dataTable = customersDataSet.Tables[1].Copy();   //Removing unwanted columns dataTable.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; #endregion   using (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 工作表中,水平方向和垂直方向都是如此。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 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 文件。最重要的是,数据显示在数字格式的表格中。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 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

标签:sheet,C#,Excel,导出,table,workbook,new
From: https://www.cnblogs.com/jianxiaoxiu/p/17673546.html

相关文章

  • go 1.21:cmp
    标准库cmp原文在这里go1.21新增cmp包提供了与有序变脸比较相关的类型和函数。Ordered定义如下:typeOrderedinterface{ ~int|~int8|~int16|~int32|~int64| ~uint|~uint8|~uint16|~uint32|~uint64|~uintptr| ~float32|~float64| ~string......
  • docker 使用Nginx反向代理配置
    dockerexec-itnginxbash#进入nginx容器容器里面需要安装Vimapt-getupdate#这个命令的作用是:同步/etc/apt/sources.list和/etc/apt/sources.list.d中列出的源的索引,这样才能获取到最新的软件包。apt-getinstall-yvim查看Nginx配置文件cdetc/nginx......
  • java POI实现导入导出功能
    导入POI库的依赖项,在项目中加入以下Maven依赖项:<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi......
  • C语言生成随机数问题
    (C语言生成随机数问题)rand函数rand-C++Reference(cplusplus.com)rand()函数是专门用来生成随机数的rand()返回的是0~RAND_MAX(32767)之间的随机数rand()函数在头文件stdlib.h中,使用前要导入这个头文件因为rand默认生成随机数范围是0~32767,这是一段很大的范围,所以我们需......
  • How to automatically run a scheduled task every hour in Node.js All In One
    HowtoautomaticallyrunascheduledtaskeveryhourinNode.jsAllInOne如何在Node.js中每间隔一小时自动运行一个定时任务引用场景Node.js后台爬虫服务,定时爬去指定页面,抓取最新数据,并写入到数据库中;在同一个Node.js部署环境中,没有使用Linux的crontab权......
  • 10个随机粒子的行为计算的软件epc2024下载
    算是一个10粒随机粒子的行为计算的软件,算是一个高级的粒子例子的数据工具,类似与一个好玩的数据玩具。Itisasoftwareforcalculatingthebehaviorof10randomparticles,anadvanceddatatoolforparticleexamples,similartoafundatatoy.本软件是Windows下的64......
  • CF 1863D 题解
    CF1863DTwo-ColoredDominoes题解Links洛谷CodeforcesDescription有一个\(n\timesm\)的棋盘,上面铺着一些\(1\times2\)的多米诺骨牌(横竖均有可能),骨牌之间没有重叠。你需要找到一种染色方案满足以下条件:每个多米诺骨牌一端被染白,另一端被染黑。其他没有骨牌的格子......
  • 东方博宜OJ 打印星号三角形 C语言版
    题目描述打印星号三角形。输入输入只有一行,包括 11 个整数 n , n 代表行数。输出输出 n 行。样例输入5输出************************************************************************......
  • SAP LSMW日志信息如何导出到Excel里?
    SAPLSMW日志信息如何导出到Excel里?在SAP系统中,数据迁移LSMW运行的日志,是可以下载到本地Excel文件里的。方式如下所示:双击某个会话,点击打印机图标,就可以导出到Excel文件里了,输入文件名,指定文件保存的目录,-完-写于2023-8-25.......
  • Flink 1.17教程:算子链Operator Chain
    算子链OperatorChain在ApacheFlink中,算子链(OperatorChaining)是将多个操作符(算子)连接在一起形成一个链式结构的优化技术。算子链的作用是将多个操作符合并为一个单一的任务单元,以减少通信开销、提高执行效率和减少资源占用。通俗来说,算子链的作用可以比喻为将多个操作合并成一......