读写Excel文件

读取单元格数据,写入单元格数据

引用NPOI程序集

 

 1 static void Main(string[] args)
 2         {
 3             string inputFile = @"C:\Users\Lenovo\Desktop\111.xlsx";
 4             string outFile = @"C:\Users\Lenovo\Desktop\222.xlsx";
 5 
 6             //加载Excel文件
 7             using (FileStream inputStream = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
 8             {
 9                 IWorkbook workbook = new XSSFWorkbook(inputStream);
10                 ISheet sheet  = workbook.GetSheetAt(0);
11 
12                 //获取数据首行和
13                 int frist = sheet.FirstRowNum;
14                 int last = sheet.LastRowNum;
15 
16                 for (int i = frist+1; i < last; i++)
17                 {
18                     //第1行 第0列 开始
19                     IRow rows = sheet.GetRow(i);
20                     ICell cells = rows.GetCell(0);
21                     
22                     //读单元格值
23                     string str = cells.ToString();
24                     str = str.Substring(0, 10);
25 
26                     //写入第一列单元格
27                     ICell cell1 = rows.CreateCell(1);
28                     cell1.SetCellValue(str);
29 
30                 }
31 
32                 //保存为新的excel文件
33                 using(FileStream outputStream = new FileStream(outFile, FileMode.Create, FileAccess.Write))
34                 {
35                     workbook.Write(outputStream);
36                 }
37             }
38 
39             Console.WriteLine("Excel file modified and saved successfully.");
40             Console.ReadKey();
41         }

 

posted @ 2023-10-10 10:01  Mr웃ZHANG  阅读(21)  评论(0编辑  收藏  举报