NuGet 添加 Syncfusion.XlsIO.WinForms

using Syncfusion.XlsIO;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;namespace Util
{public class XlsIOHelper{public static DataTable ExcelToDataTable(string fileName){DataTable dt = new DataTable();using (ExcelEngine excelEngine = new ExcelEngine()){IApplication application = excelEngine.Excel;IWorkbook workbook = application.Workbooks.Open(fileName, ExcelParseOptions.Default, true, "", ExcelVersion.Xlsx);//可以访问打开的excelIWorksheet sheet = workbook.Worksheets[0];//第一 个sheetfor (int col = 1; col <= sheet.Columns.Length; col++){if (sheet.GetText(1, col) == null) continue;dt.Columns.Add(sheet.GetText(1, col), sheet.GetValueRowCol(1, col).GetType());}for (int i = 2; i <= sheet.Rows.Length; i++){DataRow dataRow = dt.NewRow();for (int j = 1; j <= sheet.Columns.Length; j++){dataRow[j - 1] = sheet.GetValueRowCol(i, j);}dt.Rows.Add(dataRow);}}return dt;}public static void DataTableToExcel(DataTable dt, string fileName){using (ExcelEngine excelEngine = new ExcelEngine()){IApplication application = excelEngine.Excel;application.DefaultVersion = ExcelVersion.Xlsx;IWorkbook workbook = application.Workbooks.Create(1);IWorksheet sheet = workbook.Worksheets[0];DataSet customersDataSet = new DataSet();sheet.ImportDataTable(dt, true, 1, 1, true);//Creating Excel table or list object and apply style to the tableIListObject table = sheet.ListObjects.Create(dt.TableName, sheet.UsedRange);table.BuiltInTableStyle = TableBuiltInStyles.TableStyleMedium14;//Autofit the columnssheet.UsedRange.AutofitColumns();//Save the file in the given pathStream excelStream = File.Create(fileName);workbook.SaveAs(excelStream);excelStream.Dispose();//Process.Start(fileName);}}public static void DataGridViewToExcel(DataGridView dgv, string fileName){using (ExcelEngine excelEngine = new ExcelEngine()){IApplication application = excelEngine.Excel;application.DefaultVersion = ExcelVersion.Xlsx;//Create a workbook with single worksheetIWorkbook workbook = application.Workbooks.Create(1);IWorksheet worksheet = workbook.Worksheets[0];//Import from DataGridView to worksheetworksheet.ImportDataGridView(dgv, 1, 1, isImportHeader: true, isImportStyle: true);worksheet.UsedRange.AutofitColumns();workbook.SaveAs(fileName);//Process.Start(fileName);}}public static void MDBToExcel(string dBPath, string query, string fileName){using (ExcelEngine excelEngine = new ExcelEngine()){IApplication application = excelEngine.Excel;application.DefaultVersion = ExcelVersion.Xlsx;//Create a new workbookIWorkbook 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 databasesheet.ListObjects[0].Refresh();sheet.UsedRange.AutofitColumns();//Save the file in the given path//Stream excelStream = File.Create(Path.GetFullPath(@"Output.xlsx"));Stream excelStream = File.Create(fileName);workbook.SaveAs(excelStream);excelStream.Dispose();//Process.Start(fileName);}}public static void CSVToExcel(string csvFileName, string excelFileName){using (ExcelEngine excelEngine = new ExcelEngine()){IApplication application = excelEngine.Excel;application.DefaultVersion = ExcelVersion.Xlsx;//Preserve data types as per the valueapplication.PreserveCSVDataTypes = true;//Read the CSV fileStream csvStream = File.OpenRead(csvFileName); ;//Reads CSV stream as a workbookIWorkbook 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 tableTryAndUpdateGeoLocation(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 pathStream excelStream;excelStream = File.Create(excelFileName);workbook.SaveAs(excelStream);excelStream.Dispose();}}private static void TryAndUpdateGeoLocation(IListObject table, string unitString){IRange columnRange = GetListObjectColumnRange(table, unitString);if (columnRange == null) return;columnRange.Worksheet.EnableSheetCalculations();foreach (IRange range in columnRange.Cells){string currentValue = range.Value;range.Value2 = "=TEXT(TRUNC(" + currentValue + "), \"0\" & CHAR(176) & \" \") &" +" TEXT(INT((ABS(" + currentValue + ")- INT(ABS(" + currentValue + ")))*60), \"0' \") " +"& TEXT(((((ABS(" + currentValue + ")-INT(ABS(" + currentValue + ")))*60)-" +" INT((ABS(" + currentValue + ") - INT(ABS(" + currentValue + ")))*60))*60), \" 0''\")";}}private static IRange GetListObjectColumnRange(IListObject table, string name){IListObjectColumn column = table.Columns.FirstOrDefault(x => x.Name.Contains(name));if (column != null){IRange location = table.Location;return location.Worksheet[location.Row + 1, location.Column + column.Index - 1, location.LastRow, location.Column + column.Index - 1];}elsereturn null;}public static void CollectionObjToExcel<T>(IEnumerable<T> obj, string fileName){using (ExcelEngine excelEngine = new ExcelEngine()){IApplication application = excelEngine.Excel;application.DefaultVersion = ExcelVersion.Xlsx;//Create a new workbookIWorkbook workbook = application.Workbooks.Create(1);IWorksheet sheet = workbook.Worksheets[0];//Import data from customerObjects collectionsheet.ImportData(obj, 1, 1, true);#region Define StylesIStyle 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 headersheet["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;#endregionsheet.UsedRange.AutofitColumns();//Save the file in the given pathStream excelStream = File.Create(fileName);workbook.SaveAs(excelStream);excelStream.Dispose();//Process.Start(fileName);}}public static void ImportArrayToExcel(string fileName, object[] array){using (ExcelEngine excelEngine = new ExcelEngine()){IApplication application = excelEngine.Excel;application.DefaultVersion = ExcelVersion.Xlsx;//Reads input Excel stream as a workbookIWorkbook workbook = application.Workbooks.Open(fileName);//正在打开的excel不能被访问写操作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(firstRow, firstRow, ExcelInsertOptions.FormatAsBefore);//Import Peter's expenses and fill it horizontallysheet.ImportArray(array, sheet.Rows.Length + 1, 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 pathStream excelStream = File.Create(fileName);workbook.SaveAs(excelStream);excelStream.Dispose();}}}}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Util;
namespace UtilApp
{public partial class XlsIOHelperTestFrm : Form{public XlsIOHelperTestFrm(){InitializeComponent();#region Loading the data to Data GridDataSet customersDataSet = new DataSet();//Get the path of the input filestring 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;#endregion}private void button1_Click(object sender, EventArgs e){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)"};XlsIOHelper.ImportArrayToExcel(Path.GetFullPath(@"../../Data/ArrayToExcel.xlsx"), expenseArray);}private class Customers{public string SalesPerson { get; set; }public int SalesJanJune { get; set; }public int SalesJulyDec { get; set; }public int Change { get; set; }}private void button2_Click(object sender, EventArgs e){List<Customers> customers = new List<Customers>(){new  Customers(){SalesPerson="Jim Halpert",SalesJanJune = 34001,SalesJulyDec = 65001,Change = 91},new  Customers(){SalesPerson="Karen Fillippelli",SalesJanJune = 34002,SalesJulyDec = 65002,Change = 92},new  Customers(){SalesPerson="Phyllis Lapin",SalesJanJune = 34003,SalesJulyDec = 65003,Change = 93},};XlsIOHelper.CollectionObjToExcel(customers, Path.GetFullPath(@"../../Data/CollectionObjToExcel.xlsx"));}private void button3_Click(object sender, EventArgs e){XlsIOHelper.CSVToExcel(@"../../Data/TemplateSales.csv", @"../../Data/CSVToExcel.xlsx");}private void button4_Click(object sender, EventArgs e){string dBPath = Path.GetFullPath(@"../../Data/EmployeeData.mdb");string query = "SELECT EmployeeID,FirstName,LastName,Title,HireDate,Extension,ReportsTo FROM [Employees]";XlsIOHelper.MDBToExcel(dBPath, query, @"../../Data/MDBToExcel.xlsx");}private void button5_Click(object sender, EventArgs e){XlsIOHelper.DataGridViewToExcel(dataGridView1, @"../../Data/DataGridViewToExcel.xlsx");}private void button6_Click(object sender, EventArgs e){//Create a dataset from XML fileDataSet customersDataSet = new DataSet();customersDataSet.ReadXml(Path.GetFullPath(@"../../Data/Employees.xml"));//Create datatable from the datasetDataTable dataTable = new DataTable();dataTable = customersDataSet.Tables[1];XlsIOHelper.DataTableToExcel(dataTable, @"../../Data/DataTableToExcel.xlsx");}private void button7_Click(object sender, EventArgs e){DataTable dt = XlsIOHelper.ExcelToDataTable(@"../../Data/CSVToExcel.xlsx");this.dataGridView1.DataSource = dt;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;}}
}

C# Excel文件操作相关推荐

  1. python处理excel教程实例-python 读写excel文件操作示例【附源码下载】

    本文实例讲述了python 读写excel文件操作.分享给大家供大家参考,具体如下: 对excel文件的操作,python有第三方的工具包支持,xlutils,在这个工具包中包含了xlrd,xlwt等 ...

  2. python读取python源代码文件_python 读写excel文件操作示例【附源码下载】

    本文实例讲述了python 读写excel文件操作.分享给大家供大家参考,具体如下: 对excel文件的操作,python有第三方的工具包支持,xlutils,在这个工具包中包含了xlrd,xlwt等 ...

  3. day17-csv文件excel文件操作和面向对象编程

    day17 - csv文件和excel文件操作和面向对象编程(10.12) 1.python读取csv文件 python读取csv文件–读取csv文件 建立文件夹-ctrl+c–ctrl+v加入csv ...

  4. python自动化之excel文件操作

    excel文件操作 首先为什么要讲excel文件操作呢,因为一般用到的自动化框架中大部分都是用excel存放测试用例数据,是数据驱动的来源. 一.安装 本次分享的是通过openpyxl 这个模块来操作 ...

  5. matlab 环境 word 和 excel 文件操作

    matlab 环境 excel 文件操作 在本文中只讨论通过 matlab 高级函数和外部组件操作 excel 文件. excel 文件一般 读/写 方法 读取 excel 文件 利用剪贴板复制数据, ...

  6. 【Unity3D读取数据】(四)Excel文件操作(创建、读取、写入、修改)

    推荐阅读 CSDN主页 GitHub开源地址 Unity3D插件分享 简书地址 我的个人博客 QQ群:1040082875 大家好,我是佛系工程师☆恬静的小魔龙☆,不定时更新Unity开发技巧,觉得有 ...

  7. VS之Excel文件操作

    Excel是微软办公套装软件的一个重要的组成部分,它可以进行各种数据的处理.统计分析和辅助决策操作,广泛地应用于管理.统计财经.金融等众多领域. 您可以使用 Excel 创建工作簿(电子表格集合)并设 ...

  8. 用Python写个空课表生成器-Excel文件操作实例

    用Python写个空课表生成器 开发背景 刚入大学的CYQ加入了我们学校的学生会,面对繁杂的工作,能"偷懒"就"偷懒".这不,最近要举办几场活动,部门要安排人员 ...

  9. csv和excel文件操作

    csv文件读操作 什么是csv文件 csv文件叫逗号分隔值文件 每一行内容是通过逗号来区分出不同的列 csv文件可以直接通过excel打开,以行列的形式保存和显示数据,但是相对excel文件,它只能存 ...

  10. excel文件操作、多线程

    总结 # 首先导入openpyxl import openpyxl openpyxl.load_workbook(地址) - 打开现有的excel文件 openpyxl.Workbook() - 新建 ...

最新文章

  1. 浅谈错排公式的推导及应用
  2. 有关Non-cacheable,,Cacheable, non-shareable,inner-shareable,outer-shareable的理解
  3. 用Kotlin开发android平台语音识别,语义理解应用(olamisdk)
  4. 移动平台WEB前端开发技巧汇总
  5. 中国电信广东公司面试经验
  6. Leanote使用mysql_《搭建个人Leanote云笔记本》阿里云体验实验室 教程
  7. 蚂蚁集团换帅!胡晓明辞任 CEO
  8. Boot.ini无解
  9. java imagemagick 灰度,如何在imagemagick中转换灰度bmp
  10. Linux内核中的延时函数
  11. java输出汉字_java怎么 输入输出中文
  12. java实现微信支付之扫码支付
  13. 配置商用计算机,商用计算机主板配置推荐
  14. 傲腾内存 可以用ghost系统_光影精灵傲腾版笔记本安装win10系统操作教程
  15. android学习code3 布局上
  16. 如何完美卸载Mysql
  17. 26岁那年,我创业了
  18. 化妆品行业电商平台系统解决方案
  19. Marvell以太网交换芯片-88E6390x-简介
  20. 问题--[__NSCFNumber length]: unrecognized selector sent to instance 0x8b3c310’ - andy_shen

热门文章

  1. 洛谷——B2015 计算并联电阻的阻值(java)
  2. c语言点餐系统感悟,一个简单C语言点餐系统的学习心得
  3. 常用去除离群值的算法!
  4. 千万年斗转星移,小屏幕见大宇宙 - “钦天明时” 天文时钟万年历应用程序(iOS App)说明
  5. 机器学习(四)——逻辑斯蒂回归(Logistic Regression)
  6. React Native开发之——Webstorm开发RN配置
  7. 论return 0的高级写法 bushi​​​​​​​)
  8. CNN与句子分类之动态池化方法DCNN--模型介绍篇
  9. ArcGIS之克里金插值教学
  10. 【云计算的1024种玩法】一.半小时轻松搭建属于自己的Discuz论坛