asp教程.net 把多個excel匯入到多個datatable中二種方法
Microsoft.Office.Interop.Excel.Application TheExcelApp=new Microsoft.Office.Interop.Excel.Application();//預設情況下有三個工作表
TheExcelApp.Visible=false;
int colIndex,rowIndex
colIndex=1;
//第一行輸出欄位名
foreach(DataColumn dc in dt.Columns)//假設資料在dt表中
{
TheExcelApp.Worksheets("sheet1").Activate();//讓sheet1稱為當前工作表,以便寫入資料
TheExcelApp.Cells(1,colIndex).value=dc.ColumnName;
}
//從第二行開始寫入資料
for(colIndex=0;colIndex<dt.Columns.Count-1;colIndex++)
{
for(rowIndex=0;rowIndex<dt.Rows.Count-1;rowIndex++)
{
//Excle的行列都是從1開始算,所以從row+2
TheExcelApp.Cells(row+2,colIndex+1).value=dt.Rows[rowIndex][colIndex];
}
TheExcelApp.ActiveSheet.columns(colIndex+1).autofit();//自動調整寬度
}
TheExcelApp.Worksheets("sheet1").saveas(fileName);//儲存
//方法二
直接用using(養成好習慣,呵呵)。
HSSFWorkbook hssfworkbook;
void InitializeWorkbook(string path)
{
//read the template via FileStream, it is suggested to use FileAccess.Read to prevent file lock.
//book1.xls is an Excel-2007-generated file, so some new unknown BIFF records are added.
using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
}
接下來我們要開始寫最重要的函數ConvertToDataTable,即把HSSF的資料放到一個DataTable中。
HSSFSheet sheet = hssfworkbook.GetSheetAt(0);
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
while (rows.MoveNext())
{
HSSFRow row = (HSSFRow)rows.Current;
//TODO::Create DataTable row
for (int i = 0; i < row.LastCellNum; i++)
{
HSSFCell cell = row.GetCell(i);
//TODO::set cell value to the cell of DataTables
}
上面的結構大家都應該能看懂吧,無非就是先遍曆行,再遍曆行中的每一列。這裡引出了一個痛點,由於Excel的儲存格有好幾種類型,類型不同顯示的東西就不同,具體的類型有 布爾型、數值型、文本型、公式型、空白、錯誤。
public enum HSSFCellType
{
Unknown = -1,
NUMERIC = 0,
STRING = 1,
FORMULA = 2,
BLANK = 3,
BOOLEAN = 4,
ERROR = 5,
}
這裡的HSSFCellType描述了所有的類型,但細心的朋友可能已經發現了,這裡沒有日期型,這是為什麼呢?這是因為Excel底層並沒有一定 日期型,而是通過數值型來替代,至於如何區分日期和數字,都是由文本顯示的樣式決定的,在NPOI中則是由HSSFDataFormat來處理。為了能夠 方便的獲得所需要的類型所對應的文本,我們可以使用HSSFCell.ToString()來處理。
於是剛才的代碼則變成了這樣:
HSSFCell cell = row.GetCell(i);
if (cell == null)
{
dr[i] = null;
}
else
{
dr[i] = cell.ToString();
}
}
dt.Rows.Add(dr);
}