Workbook workbook = new Workbook(); //工作簿
Worksheet sheet = workbook.Worksheets[0]; //工作表
Cells cells = sheet.Cells;//单元格
sheet.Protect(ProtectionType.All, "123123", "");//保护工作表
sheet.Protection.IsSelectingLockedCellsAllowed = false;//设置只能选择解锁单元格
sheet.Protection.IsFormattingColumnsAllowed = true;//设置可以调整列
sheet.Protection.IsFormattingRowsAllowed = true;//设置可以调整行
Style style1 = workbook.Styles[workbook.Styles.Add()];//新增样式
style1.HorizontalAlignment = TextAlignmentType.Center;//文字居中
style1.Font.Name = "宋体";//文字字体
style1.Font.Size = 22;//文字大小
style1.IsLocked = false;//单元格解锁
style1.Font.IsBold = true;//粗体
style1.ForegroundColor = Color.FromArgb(0xaa, 0xcc, 0xbb);//设置背景色
style1.Pattern = BackgroundType.Solid; //设置背景样式
style1.IsTextWrapped = true;//单元格内容自动换行
style1.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin; //应用边界线 左边界线
style1.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin; //应用边界线 右边界线
style1.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin; //应用边界线 上边界线
style1.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin; //应用边界线 下边界线
cells.Merge(0, 0, 1, 5);//合并单元格
cells[0, 0].PutValue("内容");//填写内容
cells[0, 0].SetStyle(style1);//给单元格关联样式
cells.SetRowHeight(0, 20);//设置行高
cells.SetColumnWidth(1, 30);//设置列宽
cells[1, 0].Formula = "=AVERAGE(B1:E1)";//给单元格设置计算公式
//从Cells[0,0]开始创建一个2行3列的Range
Range range = ws.Cells.CreateRange(0, 0, 2, 3);
Cell cell = range[0, 0];
cell.Style.Font = 9;
range.Style = style;
range.Merge();
- 注意Range不能直接设置Style.必须先定义style再将style赋给Style.其他设置和Cell基本一致.
- Range的Style会覆盖Cell定义的Style.另外必须先赋值再传Style.否则可能不生效.
原文:https://www.cnblogs.com/weifeng123/p/8081311.html
补充一些自己使用的:
//excel表格转DataTable
DataTable dt_add = ws.Cells.ExportDataTableAsString(0, 0, ws.Cells.MaxDataRow, ws.Cells.MaxDataColumn + 1);
//在第0列、第3列的位置add两列
cells.InsertColumn(0);
cells.InsertColumn(3);
//获取cells中的内容
string str = cells[0, 0].Value.ToString();
//直接给单元格设置样式
cells[i, 0].Style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;//底部边框
cells[i, 0].Style.HorizontalAlignment = TextAlignmentType.Center;//文字居中