sunny123456

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

原文连接:https://blog.csdn.net/wangzhen209/article/details/51026472

  1. /新建工作簿
  2. Workbook workbook = new Workbook(); //工作簿
  3. Worksheet sheet = workbook.Worksheets[0]; //工作表
  4. Cells cells = sheet.Cells;//单元格
  5.  
  6. sheet.Protect(ProtectionType.All, "123123", "");//保护工作表
  7. sheet.Protection.IsSelectingLockedCellsAllowed = false;//设置只能选择解锁单元格
  8. sheet.Protection.IsFormattingColumnsAllowed = true;//设置可以调整列
  9. sheet.Protection.IsFormattingRowsAllowed = true;//设置可以调整行
  10.  
  11. Style style1 = workbook.Styles[workbook.Styles.Add()];//新增样式
  12. style1.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  13. style1.Font.Name = "宋体";//文字字体
  14. style1.Font.Size = 22;//文字大小
  15. style1.IsLocked = false;//单元格解锁
  16. style1.Font.IsBold = true;//粗体
  17. style1.ForegroundColor = Color.FromArgb(0xaa, 0xcc, 0xbb);//设置背景色
  18. style1.Pattern = BackgroundType.Solid; //设置背景样式
  19. style1.IsTextWrapped = true;//单元格内容自动换行
  20. style1.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin; //应用边界线 左边界线
  21. style1.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin; //应用边界线 右边界线
  22. style1.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin; //应用边界线 上边界线
  23. style1.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin; //应用边界线 下边界线
  24.  
  1. cells.Merge(0, 0, 1, 5);//合并单元格
  2. cells[0, 0].PutValue("内容");//填写内容
  3. cells[0, 0].SetStyle(style1);//给单元格关联样式
  4.  
  5. cells.SetRowHeight(0, 20);//设置行高
  6. cells.SetColumnWidth(1, 30);//设置列宽
  7. cells[1, 0].Formula = "=AVERAGE(B1:E1)";//给单元格设置计算公式

  1. //从Cells[0,0]开始创建一个2行3列的Range
  2. Range range = ws.Cells.CreateRange(0, 0, 2, 3);
  3. Cell cell = range[0, 0];
  4. cell.Style.Font = 9;
  5. range.Style = style;
  6. range.Merge();
  1. 注意Range不能直接设置Style.必须先定义style再将style赋给Style.其他设置和Cell基本一致.
  2. Range的Style会覆盖Cell定义的Style.另外必须先赋值再传Style.否则可能不生效.

  1. </pre><pre code_snippet_id="1630545" snippet_file_name="blog_20160331_3_2386885" name="code" class="csharp" style="margin-top: 0px; margin-bottom: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; line-height: 18px; background-color: rgb(245, 250, 254);">使用Formula:
  2. sheet.Cells[0,0].PutValue(1);
  3. sheet.Cells[1,0].PutValue(20);
  4. sheet.Cells[2,0].Formula="SUM(A1:B1)";
  5. sheet.CalculateFormula(true);
  6. Save Excel文件的时候必须调用CalculateFormula方法计算结果.

                
posted on 2020-12-31 19:45  sunny123456  阅读(538)  评论(0)    收藏  举报