CSharp操作Excel采用开源的原生.NET程序集NetOffice,格式兼容性更好。
在操作Excel的时候有时候需要合并单元格
using ExcelOffice = NetOffice.ExcelApi; using OfficeApi = NetOffice.OfficeApi; //申请一个变量 private ExcelOffice.Application excelApp; //在一个方法中定义如下 excelApp = new ExcelOffice.Application() { DisplayAlerts = false, EnableEvents = false }; //添加一个新的workbook ExcelOffice.Workbook newWorkbook = excelApp.Workbooks.Add(); //读取第一个sheet ExcelOffice.Worksheet newWorksheet = newWorkbook.Worksheets[1] as ExcelOffice.Worksheet; //合并A15到E15 newWorksheet.get_Range("A15","E15").Merge(newWorksheet.get_Range("A15","E15").MergeCells); newWorksheet.Cells[15, 1].Value = "hello world"; ExcelOffice.Range excelRange = newWorksheet.get_Range("A15", "E15"); //设置文字水平居中 excelRange.HorizontalAlignment = ExcelOffice.Enums.XlHAlign.xlHAlignCenter; //设置字体大小 excelRange.Font.Size = 15; //显示Excel excelApp.Visible = true;
希望对大家有帮助
时间: 2024-10-12 22:48:30