using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; namespace ReadExcel { class Program { static void Main(string[] args) { //要操作的excel文件路徑 string path = @"F:\zhxl\NPOI\zhxl.xlsx"; //把文件內容導入到工作薄當中,然后關閉文件 FileStream fs = File.OpenRead(path); IWorkbook workbook = new XSSFWorkbook(fs); fs.Close(); //編輯工作薄當中內容 ISheet sheet = workbook.GetSheetAt(0); for (int i = 0; i <= sheet.LastRowNum;i++ ) { foreach (ICell cell in sheet.GetRow(i).Cells) { /* * Excel數據Cell有不同的類型,當我們試圖從一個數字類型的Cell讀取出一個字符串並寫入數據庫時,就會出現Cannot get a text value from a numeric cell的異常錯誤。 * 解決辦法:先設置Cell的類型,然后就可以把純數字作為String類型讀進來了 */ cell.SetCellType(CellType.String); cell.SetCellValue((Int32.Parse(cell.StringCellValue) * 2).ToString()); } } //把編輯過后的工作薄重新保存為excel文件 FileStream fs2 = File.Create(@"F:\zhxl\NPOI\zhxl2.xlsx"); workbook.Write(fs2); fs2.Close(); } } }
程序執行后,打開生成的文件效果圖如下: