[目录]
参考
本文参考了 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.逐行读取 Excel 数据
Workbook workbook = new Workbook("D:\\Temp\\ExportTemplate-1.xlsx");
Cells cells = workbook.Worksheets[0].Cells;
for (int i = 0; i < cells.MaxDataRow + 1; i++)
{
for (int j = 0; j < cells.MaxDataColumn + 1; j++)
{
string text = cells[i, j].StringValue.Trim();
Console.Write(text + " ");
}
Console.Write("\r\n");
}
输出
编号 名称 值
1 名称1 值1
2 名称2 值2
3 名称3 值3
4 名称4 值4
5 名称5 值5
6 名称6 值6
2.读取 Excel 数据到 DataTable
//2.读取 Excel 数据到 DataTable
Workbook workbook = new Workbook("D:\\Temp\\ExportTemplate-1.xlsx");
Cells cells = workbook.Worksheets[0].Cells;
DataTable dataTable1 = cells.ExportDataTable(0, 0, cells.MaxDataRow + 1, cells.MaxColumn + 1, false);//有标题
DataTable dataTable2 = cells.ExportDataTable(0, 0, cells.MaxDataRow + 1, cells.MaxColumn + 1, true);//无标题
foreach (DataRow row in dataTable1.Rows)
{
for (int i = 0; i < row.ItemArray.Length; i++)
{
string text = row[i].ToString();
Console.Write(text + " ");
}
Console.Write("\r\n");
}
输出
编号 名称 值
1 名称1 值1
2 名称2 值2
3 名称3 值3
4 名称4 值4
5 名称5 值5
6 名称6 值6
3.根据模板写入数据到 Excel
//3.根据模板写入数据到 Excel
Workbook workbook = new Workbook();
workbook.Open("D:\\Temp\\ExportTemplate.xlsx");
Worksheet worksheet = workbook.Worksheets[0];
for (int row = 1; row < 4; row++)
{
worksheet.Cells[row, 0].PutValue("No-" + row);
worksheet.Cells[row, 1].PutValue("Name-" + row);
worksheet.Cells[row, 2].PutValue("Value-" + row);
}
workbook.Save("D:\\Temp\\ExportTemplate-2.xlsx");
输出 ExportTemplate-2.xlsx
4.根据模板写入数据到 Excel,并且合并单元格
//4.根据模板写入数据到 Excel,并且合并单元格
Workbook workbook = new Workbook();
workbook.Open("D:\\Temp\\ExportTemplate.xlsx");
Worksheet worksheet = workbook.Worksheets[0];
worksheet.Cells.InsertColumn(2);//在列序号为2的地方添加一列(序号从0开始)
string columnName = worksheet.Cells[0, 1].StringValue;//获取第一列的名称
//Merge 参数-开始行,开始列,合并行,合并列
worksheet.Cells.Merge(0, 1, 1, 2);//第0行,第1列,合并1行2列
for (int row = 1; row < 7; row++)
{
worksheet.Cells[row, 0].PutValue(row);//编号
worksheet.Cells[row, 1].PutValue("名称-" + row);
worksheet.Cells[row, 2].PutValue("子名称-" + row);
worksheet.Cells[row, 3].PutValue("值-" + row);
}
worksheet.Cells.Merge(1, 1, 3, 1);//第1行,第1列,合并3行1列
worksheet.Cells.Merge(4, 1, 3, 1);//第2行,第1列,合并3行1列
//居中的样式
Aspose.Cells.Style style = workbook.Styles[workbook.Styles.Add()];
style.HorizontalAlignment = TextAlignmentType.Center;//水平居中
style.VerticalAlignment = TextAlignmentType.Center;//垂直居中
worksheet.Cells[1, 1].SetStyle(style); //合并的单元格文字居中
worksheet.Cells[4, 1].SetStyle(style); //合并的单元格文字居中
workbook.Save("D:\\Temp\\ExportTemplate-4.xlsx");
输出 ExportTemplate-4.xlsx
5.不使用模板,直接生成 Excel
//5.不使用模板,直接生成 Excel
//(1)构造数据源
DataTable dt = new DataTable();
dt.Columns.Add("No");
dt.Columns.Add("Name");
dt.Columns.Add("Value");
for (int i = 1; i < 10; i++)
{
DataRow row = dt.NewRow();
row["No"] = i;
row["Name"] = "Name_" + i.ToString();
row["Value"] = "Value_" + i.ToString();
dt.Rows.Add(row);
}
//(2)构造 Excel
Workbook workbook = new Workbook(); //创建工作簿
Worksheet sheet = workbook.Worksheets[0]; //创建工作表
Cells cells = sheet.Cells; //单元格
//创建样式
Aspose.Cells.Style style = workbook.Styles[workbook.Styles.Add()];
style.Borders[Aspose.Cells.BorderType.LeftBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //应用边界线 左边界线
style.Borders[Aspose.Cells.BorderType.RightBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //应用边界线 右边界线
style.Borders[Aspose.Cells.BorderType.TopBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //应用边界线 上边界线
style.Borders[Aspose.Cells.BorderType.BottomBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //应用边界线 下边界线
style.HorizontalAlignment = TextAlignmentType.Center; //单元格内容的水平对齐方式文字居中
style.Font.Name = "宋体"; //字体
style.Font.IsBold = true; //设置粗体
style.Font.Size = 11; //设置字体大小
style.ForegroundColor = System.Drawing.Color.FromArgb(135, 206, 235); //天蓝色 rgb
style.Pattern = Aspose.Cells.BackgroundType.Solid; //背景样式
style.IsTextWrapped = true; //单元格内容自动换行
//表格填充数据
int Colnum = dt.Columns.Count;//表格列数
int Rownum = dt.Rows.Count;//表格行数
//生成行 列名行
for (int i = 0; i < Colnum; i++)
{
cells[0, i].PutValue(dt.Columns[i].ColumnName); //添加表头
cells[0, i].SetStyle(style); //添加样式
cells.SetColumnWidth(i, dt.Columns[i].ColumnName.Length * 2 + 3.5); //自定义列宽
cells.SetRowHeight(0, 20); //自定义高
}
//生成数据行
for (int i = 0; i < Rownum; i++)
{
for (int k = 0; k < Colnum; k++)
{
cells[1 + i, k].PutValue(dt.Rows[i][k].ToString()); //添加数据
}
//cells[i, k].Formula = "=B" + (2 + i) + "+C" + (2 + i);//给单元格设置计算公式
}
//sheet.AutoFitColumns(); //自适应宽,设置了此属性之后自定义列宽,自定义高会失效
workbook.Save("D:\\Temp\\ExportTemplate-5.xlsx"); //保存
GC.Collect();
输出 ExportTemplate-5.xlsx
6.下载 Excel
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication2.Controllers
{
public class Default1Controller : Controller
{
public FileResult Download()
{
string fileName = "ExportTemplate-5.xlsx";
string filepath = "D:\\Temp\\ExportTemplate-5.xlsx";
Stream fileStream = new FileStream(filepath, FileMode.Open);
fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
return File(fileStream, "application/octet-stream", fileName);
}
}
}
浏览器访问 http://localhost:47024/default1/download
7.操作远程文件服务器的 Excel
7.1 公共类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
using System.Runtime.InteropServices;
namespace MvcApplication2.Common
{
public class IdentityScope : IDisposable
{
// obtains user token
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
// closes open handes returned by LogonUser
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
extern static bool CloseHandle(IntPtr handle);
[DllImport("Advapi32.DLL")]
static extern bool ImpersonateLoggedOnUser(IntPtr hToken);
[DllImport("Advapi32.DLL")]
static extern bool RevertToSelf();
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_NEWCREDENTIALS = 9;//域控中的需要用:Interactive = 2
private bool disposed;
public IdentityScope(string sUsername, string sPassword, string sDomain)
{
// initialize tokens
IntPtr pExistingTokenHandle = new IntPtr(0);
IntPtr pDuplicateTokenHandle = new IntPtr(0);
try
{
// get handle to token
bool bImpersonated = LogonUser(sUsername, sDomain, sPassword,
LOGON32_LOGON_NEWCREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle);
if (true == bImpersonated)
{
if (!ImpersonateLoggedOnUser(pExistingTokenHandle))
{
int nErrorCode = Marshal.GetLastWin32Error();
throw new Exception("ImpersonateLoggedOnUser error;Code=" + nErrorCode);
}
}
else
{
int nErrorCode = Marshal.GetLastWin32Error();
throw new Exception("LogonUser error;Code=" + nErrorCode);
}
}
finally
{
// close handle(s)
if (pExistingTokenHandle != IntPtr.Zero)
CloseHandle(pExistingTokenHandle);
if (pDuplicateTokenHandle != IntPtr.Zero)
CloseHandle(pDuplicateTokenHandle);
}
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
RevertToSelf();
disposed = true;
}
}
public void Dispose()
{
Dispose(true);
}
}
}
7.2 下载
public FileResult Download1()
{
string fileName = "ExportTemplate-5.xlsx";
string filepath = "";
using (IdentityScope iss = new IdentityScope("用户名", "密码", "\\1.1.1.1"))
{
filepath = @"\\1.1.1.1\file\" + fileName;
Stream fileStream = new FileStream(filepath, FileMode.Open);
fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
return File(fileStream, "application/octet-stream", fileName);
}
}
7.3 写入 Excel
public ActionResult WriteExcel()
{
//3.根据模板写入数据到 Excel
Workbook workbook = new Workbook();
string fileName = "ExportTemplate.xlsx";
string filepath = "";
using (IdentityScope iss = new IdentityScope("用户名", "密码", "\\1.1.1.1"))
{
filepath = @"\\1.1.1.1\file\" + fileName;
workbook.Open(filepath);
}
Worksheet worksheet = workbook.Worksheets[0];
for (int row = 1; row < 4; row++)
{
worksheet.Cells[row, 0].PutValue("No-" + row);
worksheet.Cells[row, 1].PutValue("Name-" + row);
worksheet.Cells[row, 2].PutValue("Value-" + row);
}
using (IdentityScope iss = new IdentityScope("用户名", "密码", "\\1.1.1.1"))
{
filepath = @"\\1.1.1.1\file\ExportTemplate-2.xlsx";
workbook.Save(filepath);
}
return View();
}