Aspose.Cells for .NET下载地址 https://soft51.cc/software/175799451582733643
Cell 对象:代表工作表中的单个单元格,提供了读写数据、设置格式等功能。
Cells 对象:代表工作表中所有单元格的集合,提供了批量操作、区域选择等功能。
Range 对象:代表单元格区域,可以对多个单元格进行统一操作。
在 Aspose.Cells 中,有多种方式可以定位和访问单元格:
worksheet.Cells[row, column]
(从0开始)worksheet.Cells["A1"]
worksheet.Cells.GetCell(row, column)
单元格操作通常遵循以下模式:
Aspose.Cells 支持所有常见的数据类型:
PutValue(string)
DateTime
对象,可设置显示格式true
/false
=
开头的字符串写入数据:
cell.Value = data
:通用方式cell.PutValue(data)
:明确指定类型cell.Formula = "=SUM(A1:A5)"
:写入公式读取数据:
cell.Value
:获取原始值cell.StringValue
:获取字符串表示cell.IntValue
、cell.DoubleValue
:获取特定类型值cell.DateTimeValue
:获取日期时间值使用 cell.Type
属性可以判断单元格的数据类型:
CellValueType.IsString
:字符串CellValueType.IsNumeric
:数字CellValueType.IsDateTime
:日期时间CellValueType.IsBool
:布尔值CellValueType.IsNull
:空值CellValueType.IsError
:错误值Range 提供了对多个单元格的批量操作能力:
// 通过字符串创建
Range range1 = worksheet.Cells.CreateRange("A1:C3");
// 通过坐标创建
Range range2 = worksheet.Cells.CreateRange(0, 0, 3, 3);
// 通过起始位置和大小创建
Range range3 = worksheet.Cells.CreateRange("B2", 2, 2);
批量数据操作:
range.Value = array
:批量写入二维数组range.Value
:批量读取为二维数组range.Copy(targetRange)
:复制到目标区域range.MoveTo(targetRange)
:移动到目标区域批量格式操作:
range.ApplyStyle(style, flag)
:应用统一样式range.SetOutlineBorders()
:设置外边框range.SetInsideBorders()
:设置内边框range.Find(searchText, startCell, findOptions)
:查找文本range.FindNext(previousCell, findOptions)
:查找下一个range.Replace(oldText, newText, replaceOptions)
:替换文本通过 Style.Font
属性设置字体相关格式:
Font.Name
:字体名称Font.Size
:字体大小Font.Color
:字体颜色Font.IsBold
:是否粗体Font.IsItalic
:是否斜体Font.Underline
:下划线类型通过 Style
的对齐属性控制文本对齐:
HorizontalAlignment
:水平对齐(左、中、右、两端对齐等)VerticalAlignment
:垂直对齐(顶部、中间、底部)IsTextWrapped
:是否自动换行Indent
:缩进级别RotationAngle
:旋转角度边框设置:
style.SetBorder(BorderType.TopBorder, CellBorderType.Thick, Color.Black);
背景设置:
style.BackgroundColor = Color.LightBlue;
style.Pattern = BackgroundType.Solid;
通过 Style.Custom
属性设置数字显示格式:
"#,##0.00"
:千位分隔符,两位小数"0.00%"
:百分比格式"yyyy-mm-dd"
:日期格式"¥#,##0.00"
:货币格式设置公式:
cell.Formula = "=SUM(A1:A5)";
workbook.CalculateFormula(); // 计算公式
常用函数类型:
创建和使用命名区域可以让公式更易读和维护:
// 创建命名区域
workbook.Worksheets.Names.Add("SalesData", range);
// 在公式中使用
cell.Formula = "=SUM(SalesData)";
数组公式可以对整个数组进行计算:
cell.SetArrayFormula("=SUM(A1:A5*B1:B5)", 1, 1);
从 DataTable 导入:
worksheet.Cells.ImportDataTable(dataTable, true, 0, 0);
从数组导入:
worksheet.Cells.ImportArray(array, 0, 0);
从集合导入:
worksheet.Cells.ImportCustomObjects(objectList, 0, 0, new ImportTableOptions());
导出为 DataTable:
DataTable dt = worksheet.Cells.ExportDataTable(0, 0, rows, cols, new ExportTableOptions());
导出为数组:
object[,] data = worksheet.Cells.ExportArray(0, 0, rows, cols);
下面通过一个完整的学生成绩管理系统来展示单元格操作的综合应用:
using Aspose.Cells;
using System;
using System.Drawing;
public class StudentGradeManager
{
public static void CreateGradeSystem()
{
// 创建工作簿
Workbook workbook = new Workbook();
Worksheet worksheet = workbook.Worksheets[0];
worksheet.Name = "学生成绩表";
// 1. 设置标题
worksheet.Cells["A1"].Value = "学生成绩管理系统";
worksheet.Cells.Merge(0, 0, 1, 7);
Style titleStyle = workbook.CreateStyle();
titleStyle.Font.Size = 16;
titleStyle.Font.IsBold = true;
titleStyle.HorizontalAlignment = TextAlignmentType.Center;
titleStyle.BackgroundColor = Color.Navy;
titleStyle.Font.Color = Color.White;
titleStyle.Pattern = BackgroundType.Solid;
worksheet.Cells["A1"].SetStyle(titleStyle);
// 2. 设置列标题
string[] headers = {"学号", "姓名", "数学", "英语", "语文", "总分", "平均分", "等级"};
for (int i = 0; i < headers.Length; i++)
{
Cell headerCell = worksheet.Cells[2, i];
headerCell.Value = headers[i];
Style headerStyle = workbook.CreateStyle();
headerStyle.BackgroundColor = Color.LightBlue;
headerStyle.Pattern = BackgroundType.Solid;
headerStyle.Font.IsBold = true;
headerStyle.HorizontalAlignment = TextAlignmentType.Center;
headerStyle.SetBorder(BorderType.TopBorder, CellBorderType.Thin, Color.Black);
headerStyle.SetBorder(BorderType.BottomBorder, CellBorderType.Thin, Color.Black);
headerStyle.SetBorder(BorderType.LeftBorder, CellBorderType.Thin, Color.Black);
headerStyle.SetBorder(BorderType.RightBorder, CellBorderType.Thin, Color.Black);
headerCell.SetStyle(headerStyle);
}
// 3. 创建学生数据
object[,] studentData = {
{"S001", "张三", 85, 78, 92},
{"S002", "李四", 92, 88, 85},
{"S003", "王五", 78, 85, 90},
{"S004", "赵六", 88, 92, 78},
{"S005", "钱七", 95, 85, 88}
};
// 4. 批量写入基础数据
Range dataRange = worksheet.Cells.CreateRange(3, 0, 5, 5);
dataRange.Value = studentData;
// 5. 设置公式
for (int row = 3; row < 8; row++)
{
// 总分公式
worksheet.Cells[row, 5].Formula = $"=SUM(C{row+1}:E{row+1})";
// 平均分公式
worksheet.Cells[row, 6].Formula = $"=AVERAGE(C{row+1}:E{row+1})";
// 等级公式
worksheet.Cells[row, 7].Formula =
$"=IF(G{row+1}>=90,\"优秀\",IF(G{row+1}>=80,\"良好\",IF(G{row+1}>=70,\"中等\",\"及格\")))";
}
// 6. 计算公式
workbook.CalculateFormula();
// 7. 设置数据区域格式
Range allDataRange = worksheet.Cells.CreateRange("A3:H8");
Style dataStyle = workbook.CreateStyle();
dataStyle.SetBorder(BorderType.TopBorder, CellBorderType.Thin, Color.Gray);
dataStyle.SetBorder(BorderType.BottomBorder, CellBorderType.Thin, Color.Gray);
dataStyle.SetBorder(BorderType.LeftBorder, CellBorderType.Thin, Color.Gray);
dataStyle.SetBorder(BorderType.RightBorder, CellBorderType.Thin, Color.Gray);
dataStyle.HorizontalAlignment = TextAlignmentType.Center;
StyleFlag flag = new StyleFlag();
flag.Borders = true;
flag.HorizontalAlignment = true;
allDataRange.ApplyStyle(dataStyle, flag);
// 8. 设置数字格式
Range scoreRange = worksheet.Cells.CreateRange("C4:G8");
Style numberStyle = workbook.CreateStyle();
numberStyle.Custom = "0.00";
scoreRange.ApplyStyle(numberStyle, new StyleFlag { NumberFormat = true });
// 9. 添加条件格式化
// 优秀成绩高亮
FormatCondition excellentCondition = worksheet.ConditionalFormattings.AddCondition(
FormatConditionType.CellValue, OperatorType.GreaterOrEqual, "90", null);
excellentCondition.Areas.Add(worksheet.Cells.CreateCellArea("G4", "G8"));
excellentCondition.Style.BackgroundColor = Color.LightGreen;
excellentCondition.Style.Pattern = BackgroundType.Solid;
// 不及格成绩高亮
FormatCondition failCondition = worksheet.ConditionalFormattings.AddCondition(
FormatConditionType.CellValue, OperatorType.Less, "60", null);
failCondition.Areas.Add(worksheet.Cells.CreateCellArea("G4", "G8"));
failCondition.Style.BackgroundColor = Color.LightCoral;
failCondition.Style.Pattern = BackgroundType.Solid;
// 10. 添加统计信息
worksheet.Cells["A10"].Value = "统计信息";
worksheet.Cells["A11"].Value = "班级人数:";
worksheet.Cells["B11"].Formula = "=COUNTA(A4:A8)";
worksheet.Cells["A12"].Value = "平均总分:";
worksheet.Cells["B12"].Formula = "=AVERAGE(F4:F8)";
worksheet.Cells["A13"].Value = "最高分:";
worksheet.Cells["B13"].Formula = "=MAX(F4:F8)";
worksheet.Cells["A14"].Value = "优秀人数:";
worksheet.Cells["B14"].Formula = "=COUNTIF(H4:H8,\"优秀\")";
// 11. 设置列宽和行高
worksheet.AutoFitColumns();
worksheet.Cells.SetRowHeight(0, 30);
worksheet.Cells.SetRowHeight(2, 25);
// 12. 数据验证(为新增数据行预设)
Range validationRange = worksheet.Cells.CreateRange("C9:E20");
Validation validation = worksheet.Validations[worksheet.Validations.Add()];
validation.AreaList.Add(validationRange);
validation.Type = ValidationType.Decimal;
validation.Operator = OperatorType.Between;
validation.Formula1 = "0";
validation.Formula2 = "100";
validation.ErrorMessage = "请输入0-100之间的分数";
validation.ShowError = true;
// 13. 保存文件
workbook.Save("StudentGradeManagement.xlsx");
Console.WriteLine("学生成绩管理系统创建完成!");
// 14. 演示数据读取
Console.WriteLine("\n学生成绩统计:");
for (int row = 3; row < 8; row++)
{
string studentId = worksheet.Cells[row, 0].StringValue;
string name = worksheet.Cells[row, 1].StringValue;
double total = worksheet.Cells[row, 5].DoubleValue;
double average = worksheet.Cells[row, 6].DoubleValue;
string grade = worksheet.Cells[row, 7].StringValue;
Console.WriteLine($"{studentId} {name}: 总分{total:F1}, 平均分{average:F1}, 等级{grade}");
}
// 15. 演示批量数据导出
object[,] exportData = worksheet.Cells.ExportArray(2, 0, 6, 8);
Console.WriteLine($"\n导出数据: {exportData.GetLength(0)}行 x {exportData.GetLength(1)}列");
}
}
// 使用示例
class Program
{
static void Main(string[] args)
{
try
{
StudentGradeManager.CreateGradeSystem();
Console.WriteLine("程序执行完成,请查看生成的Excel文件。");
}
catch (Exception ex)
{
Console.WriteLine($"程序执行出错: {ex.Message}");
}
Console.ReadKey();
}
}
批量操作优先:
样式优化:
公式优化:
及时释放资源:
// 处理完成后释放大对象
largeArray = null;
GC.Collect();
分批处理大数据:
int batchSize = 1000;
for (int i = 0; i < totalRows; i += batchSize)
{
// 分批处理数据
}
数据验证:
异常捕获:
try
{
// 单元格操作代码
}
catch (CellsException ex)
{
Console.WriteLine($"单元格操作错误: {ex.Message}");
}
通过掌握这些单元格操作技巧,你可以高效地处理 Excel 文件中的数据读写、格式设置和批量操作,为构建复杂的电子表格应用程序奠定坚实的基础。
Aspose.Cells for .NET下载地址 https://soft51.cc/software/175799451582733643