代码改变世界

使用C#和Excel进行报表开发(5)

  观海看云  阅读(131)  评论(0编辑  收藏  举报

内容摘要:在用Excel作报表的时候,可能需要操作单元格的边框和填充颜色和纹理等操作,下面的代码说明如何设置选中的单元格的填充纹理和边框。

  在用Excel作报表的时候,可能需要操作单元格的边框和填充颜色和纹理等操作,下面的代码说明如何设置选中的单元格的填充纹理和边框。

  try
  {
   ThisApplication = new Excel.Application();  ThisWorkbook = ThisApplication.Workbooks.Open("z:Book1.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);   ThisApplication.DisplayAlerts = false;
   xlSheet = (Excel.Worksheet)ThisWorkbook.Worksheets.get_Item(1);
   Excel.Range range = xlSheet.get_Range("G4","H5");
   range.Value = "123";
   Excel.Style st = ThisWorkbook.Styles.Add("PropertyBorder", Type.Missing);
   range.Interior.Pattern = Excel.XlPattern.xlPatternCrissCross;
  range.Borders.Weight = 2;
   range.Borders.get_Item(XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlLineStyle.xlContinuous;
  range.Borders.get_Item(XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlContinuous;
  range.Borders.get_Item(XlBordersIndex.xlEdgeTop).LineStyle = Excel.XlLineStyle.xlContinuous;
  range.Borders.get_Item(XlBordersIndex.xlDiagonalDown).LineStyle = Excel.XlLineStyle.xlLineStyleNone;
  range.Borders.get_Item(XlBordersIndex.xlDiagonalUp).LineStyle = Excel.XlLineStyle.xlLineStyleNone;
  range.Borders.get_Item(XlBordersIndex.xlInsideHorizontal).LineStyle = Excel.XlLineStyle.xlLineStyleNone;
  range.Borders.get_Item(XlBordersIndex.xlInsideVertical).LineStyle = Excel.XlLineStyle.xlLineStyleNone;
  range.Borders.get_Item(XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlLineStyle.xlDot;
  range.Borders.get_Item(XlBordersIndex.xlEdgeLeft).Color = System.Drawing.ColorTranslator.ToOle(Color.Red);
   ThisWorkbook.SaveAs("z:Book2.xls", Type.Missing, Type.Missing,
  Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange,
  Type.Missing, Type.Missing, Type.Missing, Type.Missing);
  }
  catch (Exception ex)
  {
   MessageBox.Show(ex.Message);
  }
  finally
  {
   ThisWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
   ThisApplication.Workbooks.Close();   ThisApplication.Quit();
  System.Runtime.InteropServices.Marshal.ReleaseComObject(ThisWorkbook);
  System.Runtime.InteropServices.Marshal.ReleaseComObject(ThisApplication);
   ThisWorkbook = null;
   ThisApplication = null;
   GC.Collect();
   this.Close();
  }

 

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
点击右上角即可分享
微信分享提示