內容包含 :
選擇檔案 System.Windows.Forms OpenFileDialog
串讀Excel資料丟入HSSF處理
using System.Windows.Forms;
using System.IO;
using NPOI.HSSF.UserModel;
選擇上傳檔案
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "Select file";
dialog.InitialDirectory = ".\\";
dialog.Filter = "xls files (*.xls)|*.xls";
dialog.Multiselect = true;
if (dialog.ShowDialog() == DialogResult.OK)
{
excelFiles = new List<string>();
string filenames = "";
foreach (string file in dialog.FileNames)
{
//儲存選擇的EXCEL的路徑
excelFiles.Add(file);
if (string.IsNullOrEmpty(filenames)) filenames = file;
else filenames += "; " + file;
}
textBox1.Text = filenames;
label1.Text = excelFiles.Count + " excel file";
if (excelFiles.Count == 1) label1.Text += " is selected.";
else label1.Text += "s are selected.";
button2.Enabled = true;
button2.Focus();
}
upload資料 & HSSFWorkbook
using System.IO;
using NPOI.HSSF.UserModel
byte[] bytes;.
// 讀取上傳資料
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
bytes = new byte[fs.Length];
fs.Read(bytes, 0, (int)fs.Length);
}
Stream stream = new MemoryStream(bytes);
HSSFWorkbook hssfwb = new HSSFWorkbook(stream);
string sheetName = hssfwb.GetSheetName(0);
//抓取某sheet
ISheet sheet = hssfwb.GetSheet(sheetName);
//抓取某Row 某column
ss.Name= sheet.GetRow(0).GetCell(0).ToString();