C# 導出Excel的6種簡單方法實現

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

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 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 工作表中,水平方向和垂直方向都是如此。

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翻譯,轉載請註明來源出處。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章