使用 Aspose.Cells 操作 Excel(包含登录远程服务器操作 Excel)

2019年07月11日 17:00 · 阅读(2572) ·

[目录]

参考

本文参考了 C# Aspose.Cells.dll Excel操作总结 文章,结合自己的实际操作过程写成

Aspose.Cells 简介

Aspose.Cells for .NET是一款Excel编程产品包,它是一套API与GUI控件组合,它可以帮助开发者在应用程序中操作与转换电子表格文件。

这个Excel spreadsheet API提供给开发者强有力的工具来操作简单文件转换和复杂的任务。帮助开发者控制页面布局,格式,图像与公式。可以帮助他们读写电子表格文件并保存成各种图像,便携式和文本文件格式。

Aspose.Cells for .NET产品具备快速可靠特点。它可以帮助你节省更多的时间与精力开发你自己需要的电子表格操作或使用微软自动化软件的解决方案。

Aspose.Cells 下载

见附件

测试 Excel

见附件

ExportTemplate.xlsx

ExportTemplate-1.xlsx

引用 dll

1.逐行读取 Excel 数据

  1. //1.逐行读取 Excel 数据
  2. Workbook workbook = new Workbook("D:\\Temp\\ExportTemplate-1.xlsx");
  3. Cells cells = workbook.Worksheets[0].Cells;
  4. for (int i = 0; i < cells.MaxDataRow + 1; i++)
  5. {
  6. for (int j = 0; j < cells.MaxDataColumn + 1; j++)
  7. {
  8. string text = cells[i, j].StringValue.Trim();
  9. Console.Write(text + " ");
  10. }
  11. Console.Write("\r\n");
  12. }

输出

  1. 编号 名称
  2. 1 名称1 1
  3. 2 名称2 2
  4. 3 名称3 3
  5. 4 名称4 4
  6. 5 名称5 5
  7. 6 名称6 6

2.读取 Excel 数据到 DataTable

  1. //2.读取 Excel 数据到 DataTable
  2. Workbook workbook = new Workbook("D:\\Temp\\ExportTemplate-1.xlsx");
  3. Cells cells = workbook.Worksheets[0].Cells;
  4. DataTable dataTable1 = cells.ExportDataTable(0, 0, cells.MaxDataRow + 1, cells.MaxColumn + 1, false);//有标题
  5. DataTable dataTable2 = cells.ExportDataTable(0, 0, cells.MaxDataRow + 1, cells.MaxColumn + 1, true);//无标题
  6. foreach (DataRow row in dataTable1.Rows)
  7. {
  8. for (int i = 0; i < row.ItemArray.Length; i++)
  9. {
  10. string text = row[i].ToString();
  11. Console.Write(text + " ");
  12. }
  13. Console.Write("\r\n");
  14. }

输出

  1. 编号 名称
  2. 1 名称1 1
  3. 2 名称2 2
  4. 3 名称3 3
  5. 4 名称4 4
  6. 5 名称5 5
  7. 6 名称6 6

3.根据模板写入数据到 Excel

  1. //3.根据模板写入数据到 Excel
  2. Workbook workbook = new Workbook();
  3. workbook.Open("D:\\Temp\\ExportTemplate.xlsx");
  4. Worksheet worksheet = workbook.Worksheets[0];
  5. for (int row = 1; row < 4; row++)
  6. {
  7. worksheet.Cells[row, 0].PutValue("No-" + row);
  8. worksheet.Cells[row, 1].PutValue("Name-" + row);
  9. worksheet.Cells[row, 2].PutValue("Value-" + row);
  10. }
  11. workbook.Save("D:\\Temp\\ExportTemplate-2.xlsx");

输出 ExportTemplate-2.xlsx

4.根据模板写入数据到 Excel,并且合并单元格

  1. //4.根据模板写入数据到 Excel,并且合并单元格
  2. Workbook workbook = new Workbook();
  3. workbook.Open("D:\\Temp\\ExportTemplate.xlsx");
  4. Worksheet worksheet = workbook.Worksheets[0];
  5. worksheet.Cells.InsertColumn(2);//在列序号为2的地方添加一列(序号从0开始)
  6. string columnName = worksheet.Cells[0, 1].StringValue;//获取第一列的名称
  7. //Merge 参数-开始行,开始列,合并行,合并列
  8. worksheet.Cells.Merge(0, 1, 1, 2);//第0行,第1列,合并1行2列
  9. for (int row = 1; row < 7; row++)
  10. {
  11. worksheet.Cells[row, 0].PutValue(row);//编号
  12. worksheet.Cells[row, 1].PutValue("名称-" + row);
  13. worksheet.Cells[row, 2].PutValue("子名称-" + row);
  14. worksheet.Cells[row, 3].PutValue("值-" + row);
  15. }
  16. worksheet.Cells.Merge(1, 1, 3, 1);//第1行,第1列,合并3行1列
  17. worksheet.Cells.Merge(4, 1, 3, 1);//第2行,第1列,合并3行1列
  18. //居中的样式
  19. Aspose.Cells.Style style = workbook.Styles[workbook.Styles.Add()];
  20. style.HorizontalAlignment = TextAlignmentType.Center;//水平居中
  21. style.VerticalAlignment = TextAlignmentType.Center;//垂直居中
  22. worksheet.Cells[1, 1].SetStyle(style); //合并的单元格文字居中
  23. worksheet.Cells[4, 1].SetStyle(style); //合并的单元格文字居中
  24. workbook.Save("D:\\Temp\\ExportTemplate-4.xlsx");

输出 ExportTemplate-4.xlsx

5.不使用模板,直接生成 Excel

  1. //5.不使用模板,直接生成 Excel
  2. //(1)构造数据源
  3. DataTable dt = new DataTable();
  4. dt.Columns.Add("No");
  5. dt.Columns.Add("Name");
  6. dt.Columns.Add("Value");
  7. for (int i = 1; i < 10; i++)
  8. {
  9. DataRow row = dt.NewRow();
  10. row["No"] = i;
  11. row["Name"] = "Name_" + i.ToString();
  12. row["Value"] = "Value_" + i.ToString();
  13. dt.Rows.Add(row);
  14. }
  15. //(2)构造 Excel
  16. Workbook workbook = new Workbook(); //创建工作簿
  17. Worksheet sheet = workbook.Worksheets[0]; //创建工作表
  18. Cells cells = sheet.Cells; //单元格
  19. //创建样式
  20. Aspose.Cells.Style style = workbook.Styles[workbook.Styles.Add()];
  21. style.Borders[Aspose.Cells.BorderType.LeftBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //应用边界线 左边界线
  22. style.Borders[Aspose.Cells.BorderType.RightBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //应用边界线 右边界线
  23. style.Borders[Aspose.Cells.BorderType.TopBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //应用边界线 上边界线
  24. style.Borders[Aspose.Cells.BorderType.BottomBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //应用边界线 下边界线
  25. style.HorizontalAlignment = TextAlignmentType.Center; //单元格内容的水平对齐方式文字居中
  26. style.Font.Name = "宋体"; //字体
  27. style.Font.IsBold = true; //设置粗体
  28. style.Font.Size = 11; //设置字体大小
  29. style.ForegroundColor = System.Drawing.Color.FromArgb(135, 206, 235); //天蓝色 rgb
  30. style.Pattern = Aspose.Cells.BackgroundType.Solid; //背景样式
  31. style.IsTextWrapped = true; //单元格内容自动换行
  32. //表格填充数据
  33. int Colnum = dt.Columns.Count;//表格列数
  34. int Rownum = dt.Rows.Count;//表格行数
  35. //生成行 列名行
  36. for (int i = 0; i < Colnum; i++)
  37. {
  38. cells[0, i].PutValue(dt.Columns[i].ColumnName); //添加表头
  39. cells[0, i].SetStyle(style); //添加样式
  40. cells.SetColumnWidth(i, dt.Columns[i].ColumnName.Length * 2 + 3.5); //自定义列宽
  41. cells.SetRowHeight(0, 20); //自定义高
  42. }
  43. //生成数据行
  44. for (int i = 0; i < Rownum; i++)
  45. {
  46. for (int k = 0; k < Colnum; k++)
  47. {
  48. cells[1 + i, k].PutValue(dt.Rows[i][k].ToString()); //添加数据
  49. }
  50. //cells[i, k].Formula = "=B" + (2 + i) + "+C" + (2 + i);//给单元格设置计算公式
  51. }
  52. //sheet.AutoFitColumns(); //自适应宽,设置了此属性之后自定义列宽,自定义高会失效
  53. workbook.Save("D:\\Temp\\ExportTemplate-5.xlsx"); //保存
  54. GC.Collect();

输出 ExportTemplate-5.xlsx

6.下载 Excel

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Web;
  6. using System.Web.Mvc;
  7. namespace MvcApplication2.Controllers
  8. {
  9. public class Default1Controller : Controller
  10. {
  11. public FileResult Download()
  12. {
  13. string fileName = "ExportTemplate-5.xlsx";
  14. string filepath = "D:\\Temp\\ExportTemplate-5.xlsx";
  15. Stream fileStream = new FileStream(filepath, FileMode.Open);
  16. fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
  17. return File(fileStream, "application/octet-stream", fileName);
  18. }
  19. }
  20. }

浏览器访问 http://localhost:47024/default1/download

7.操作远程文件服务器的 Excel

7.1 公共类

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Data;
  6. using System.Reflection;
  7. using System.ComponentModel.DataAnnotations;
  8. using System.Runtime.InteropServices;
  9. namespace MvcApplication2.Common
  10. {
  11. public class IdentityScope : IDisposable
  12. {
  13. // obtains user token
  14. [DllImport("advapi32.dll", SetLastError = true)]
  15. static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword,
  16. int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
  17. // closes open handes returned by LogonUser
  18. [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
  19. extern static bool CloseHandle(IntPtr handle);
  20. [DllImport("Advapi32.DLL")]
  21. static extern bool ImpersonateLoggedOnUser(IntPtr hToken);
  22. [DllImport("Advapi32.DLL")]
  23. static extern bool RevertToSelf();
  24. const int LOGON32_PROVIDER_DEFAULT = 0;
  25. const int LOGON32_LOGON_NEWCREDENTIALS = 9;//域控中的需要用:Interactive = 2
  26. private bool disposed;
  27. public IdentityScope(string sUsername, string sPassword, string sDomain)
  28. {
  29. // initialize tokens
  30. IntPtr pExistingTokenHandle = new IntPtr(0);
  31. IntPtr pDuplicateTokenHandle = new IntPtr(0);
  32. try
  33. {
  34. // get handle to token
  35. bool bImpersonated = LogonUser(sUsername, sDomain, sPassword,
  36. LOGON32_LOGON_NEWCREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle);
  37. if (true == bImpersonated)
  38. {
  39. if (!ImpersonateLoggedOnUser(pExistingTokenHandle))
  40. {
  41. int nErrorCode = Marshal.GetLastWin32Error();
  42. throw new Exception("ImpersonateLoggedOnUser error;Code=" + nErrorCode);
  43. }
  44. }
  45. else
  46. {
  47. int nErrorCode = Marshal.GetLastWin32Error();
  48. throw new Exception("LogonUser error;Code=" + nErrorCode);
  49. }
  50. }
  51. finally
  52. {
  53. // close handle(s)
  54. if (pExistingTokenHandle != IntPtr.Zero)
  55. CloseHandle(pExistingTokenHandle);
  56. if (pDuplicateTokenHandle != IntPtr.Zero)
  57. CloseHandle(pDuplicateTokenHandle);
  58. }
  59. }
  60. protected virtual void Dispose(bool disposing)
  61. {
  62. if (!disposed)
  63. {
  64. RevertToSelf();
  65. disposed = true;
  66. }
  67. }
  68. public void Dispose()
  69. {
  70. Dispose(true);
  71. }
  72. }
  73. }

7.2 下载

  1. public FileResult Download1()
  2. {
  3. string fileName = "ExportTemplate-5.xlsx";
  4. string filepath = "";
  5. using (IdentityScope iss = new IdentityScope("用户名", "密码", "\\1.1.1.1"))
  6. {
  7. filepath = @"\\1.1.1.1\file\" + fileName;
  8. Stream fileStream = new FileStream(filepath, FileMode.Open);
  9. fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
  10. return File(fileStream, "application/octet-stream", fileName);
  11. }
  12. }

7.3 写入 Excel

  1. public ActionResult WriteExcel()
  2. {
  3. //3.根据模板写入数据到 Excel
  4. Workbook workbook = new Workbook();
  5. string fileName = "ExportTemplate.xlsx";
  6. string filepath = "";
  7. using (IdentityScope iss = new IdentityScope("用户名", "密码", "\\1.1.1.1"))
  8. {
  9. filepath = @"\\1.1.1.1\file\" + fileName;
  10. workbook.Open(filepath);
  11. }
  12. Worksheet worksheet = workbook.Worksheets[0];
  13. for (int row = 1; row < 4; row++)
  14. {
  15. worksheet.Cells[row, 0].PutValue("No-" + row);
  16. worksheet.Cells[row, 1].PutValue("Name-" + row);
  17. worksheet.Cells[row, 2].PutValue("Value-" + row);
  18. }
  19. using (IdentityScope iss = new IdentityScope("用户名", "密码", "\\1.1.1.1"))
  20. {
  21. filepath = @"\\1.1.1.1\file\ExportTemplate-2.xlsx";
  22. workbook.Save(filepath);
  23. }
  24. return View();
  25. }

相关附件 Aspose.Cells | 大小:3.45M | 下载 ExportTemplate | 大小:0.01M | 下载 ExportTemplate-1 | 大小:0.01M | 下载