使用EPPLUS操作EXcel
时间 2014-11-06 19:28:01 姜糖水
原文 http://www.cnphp6.com/archives/58648
主题 Excel
1 下载Epplus最新版: http://epplus.codeplex.com/
2 在项目中添加引用 EEPULS.dll(测试环境Win7+V2010旗舰)
3 添加using引用
using OfficeOpenXml;
using OfficeOpenXml.Drawing;
using OfficeOpenXml.Drawing.Chart;
using OfficeOpenXml.Style;
4 read Excel文件
private void button2_Click(object sender, EventArgs e) { string pfilePath = ""; OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "*.xls|*.xlsx"; if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { pfilePath = ofd.FileName; } if (string.IsNullOrEmpty(pfilePath)) { MessageBox.Show("没有选中文件"); return; } FileInfo existingFile = new FileInfo(pfilePath); try { ExcelPackage package = new ExcelPackage(existingFile); int vSheetCount = package.Workbook.Worksheets.Count; //获取总Sheet页 ExcelWorksheet worksheet = package.Workbook.Worksheets[1];//选定 指定页 int maxColumnNum = worksheet.Dimension.End.Column;//最大列 int minColumnNum = worksheet.Dimension.Start.Column;//最小列 int maxRowNum = worksheet.Dimension.End.Row;//最小行 int minRowNum = worksheet.Dimension.Start.Row;//最大行 DataTable vTable = new DataTable(); DataColumn vC; for (int j = 1; j <= maxColumnNum; j++) { vC = new DataColumn("A_" + j, typeof(string)); vTable.Columns.Add(vC); } if (maxRowNum > 200) { maxRowNum = 200; } for (int n = 1; n <= maxRowNum; n++) { DataRow vRow = vTable.NewRow(); for (int m = 1; m <= maxColumnNum; m++) { vRow[m - 1] = worksheet.Cells[n, m].Value; } vTable.Rows.Add(vRow); } this.dataGridView1.DataSource = vTable; } catch (Exception vErr) { MessageBox.Show(vErr.Message); } }
5 write Excel文件
private void button1_Click(object sender, EventArgs e) { OfficeOpenXml.ExcelPackage ep = new OfficeOpenXml.ExcelPackage(); OfficeOpenXml.ExcelWorkbook wb = ep.Workbook; OfficeOpenXml.ExcelWorksheet ws = wb.Worksheets.Add("我的工作表"); //配置文件属性 wb.Properties.Category = "类别"; wb.Properties.Author = "作者"; wb.Properties.Comments = "备注"; wb.Properties.Company = "公司"; wb.Properties.Keywords = "关键字"; wb.Properties.Manager = "管理者"; wb.Properties.Status = "内容状态"; wb.Properties.Subject = "主题"; wb.Properties.Title = "标题"; wb.Properties.LastModifiedBy = "最后一次保存者"; //写数据 ws.Cells[1, 1].Value = "Hello"; ws.Column(1).Width=40;//修改列宽 ws.Cells["B1"].Value = "World"; ws.Cells[3, 3, 3, 5].Merge = true; ws.Cells[3, 3].Value = "Cells[3, 3, 3, 5]合并"; ws.Cells["A4:D5"].Merge = true; ws.Cells["A4"].Value = "Cells[\"A4:D5\"]合并"; SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "*.xls|*.xlsx"; if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { FileInfo file = new FileInfo(sfd.FileName); ep.File = file; ep.Save(); MessageBox.Show("保存成功"); } else { MessageBox.Show("取消保存"); } }
上述代码大部分来源网络,只进行过小改动,下面是原文和资料地址:
http://blog.csdn.net/jimmy2248/article/details/8363697
http://blog.csdn.net/zhoufoxcn/article/details/14112473
http://www.cnblogs.com/liudeyun/p/3535740.html
http://blog.163.com/china__xuhua/blog/static/19972316920136335721285/
时间: 2024-11-05 16:31:34