C# 对Excel 单元格格式, 及行高、 列宽、 单元格边框线、 冻结设置
时间: 2023-08-24 19:05:24 浏览: 715
C sharp设置excel格式l.docx
C# 可以使用 Microsoft.Office.Interop.Excel 库来对 Excel 单元格格式、行高、列宽、单元格边框线以及冻结设置进行操作。
下面是一些常见的操作示例:
1. 设置单元格的值和格式:
```csharp
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excel = new Excel.Application();
Excel.Workbook workbook = excel.Workbooks.Open("文件路径");
Excel.Worksheet worksheet = workbook.Sheets[1];
Excel.Range range = worksheet.Cells[1, 1];
range.Value2 = "这是一个字符串";
range.NumberFormat = "0.00"; // 设置单元格格式为数字,保留两位小数
workbook.Save();
workbook.Close();
excel.Quit();
```
2. 设置行高和列宽:
```csharp
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excel = new Excel.Application();
Excel.Workbook workbook = excel.Workbooks.Open("文件路径");
Excel.Worksheet worksheet = workbook.Sheets[1];
Excel.Range range = worksheet.Cells[1, 1];
range.EntireRow.RowHeight = 30; // 设置第一行的行高为30
range.EntireColumn.ColumnWidth = 20; // 设置第一列的列宽为20
workbook.Save();
workbook.Close();
excel.Quit();
```
3. 设置单元格边框线:
```csharp
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excel = new Excel.Application();
Excel.Workbook workbook = excel.Workbooks.Open("文件路径");
Excel.Worksheet worksheet = workbook.Sheets[1];
Excel.Range range = worksheet.Cells[1, 1];
Excel.Borders borders = range.Borders;
borders.LineStyle = Excel.XlLineStyle.xlContinuous; // 设置边框线样式为实线
borders.Weight = Excel.XlBorderWeight.xlThin; // 设置边框线粗细
workbook.Save();
workbook.Close();
excel.Quit();
```
4. 冻结设置:
```csharp
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excel = new Excel.Application();
Excel.Workbook workbook = excel.Workbooks.Open("文件路径");
Excel.Worksheet worksheet = workbook.Sheets[1];
worksheet.Application.ActiveWindow.SplitRow = 1; // 冻结第一行
worksheet.Application.ActiveWindow.SplitColumn = 0; // 不冻结列
workbook.Save();
workbook.Close();
excel.Quit();
```
注意:在使用完毕后,需要关闭 Excel 进程,否则可能会导致内存泄漏问题。
阅读全文