//NPOI將檔案加入參考後引入 using NPOI; using NPOI.HSSF; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; //資料存放位置 private static string[] myData; private static List<string[]> arrMyData; private void button1_Click_1(object sender, EventArgs e) { //載入excel OpenFileDialog OpenFileDig = new OpenFileDialog(); //限制副檔名為 *.xls OpenFileDig.Filter = "xls Files|*.xls"; OpenFileDig.Title = "Select a xls File"; if (OpenFileDig.ShowDialog() == DialogResult.OK) { //將路徑顯示在 LAB上 labDir.Text = OpenFileDig.FileName.ToString(); FileName = OpenFileDig.FileName.ToString(); strPath = FileName.Replace(OpenFileDig.SafeFileName.ToString(), ""); } //初始化要存放資料的地方(此為泛字串陣列) arrMyData = new List<string[]>(); HSSFWorkbook wk; HSSFSheet hst; HSSFRow hr; try { using (FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.ReadWrite)) { wk = new HSSFWorkbook(fs); } //預設為第一張表 如要讀取其他工作表 請更改下面的值 0,1,2,3,4‧‧‧ hst = (HSSFSheet)wk.GetSheetAt(0); #region Get Sheet Name //strSheetname = hst.SheetName; #endregion Get Sheet Name //取得標題 hr = (HSSFRow)hst.GetRow(0); //取得欄位數量 int dLastNum = hr.LastCellNum; //有多少筆資料 j=1 有標題,j=0 無標題 (從哪開始讀取資料) for (int j = 1; j <= hst.LastRowNum; j++) { hr = (HSSFRow)hst.GetRow(j); //宣告陣列 並將資料同時置入 myData = new string[1] { hr.GetCell(0) == null ? "" : hr.GetCell(0).ToString(), //如果儲存格資料為空白null 將""加入陣列 hr.GetCell(1) == null ? "" : hr.GetCell(1).ToString() //欄位有多少 則新增多少 }; //將每一行的資料存放至arrMyData儲存 ,之後要做什麼應用取得 arrMyData 即可~ arrMyData.Add(myData); } } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } }
想知道更多請點擊參考