注意要先添加程序集的引用ide
導出到excel:spa
public override IWorkbook writeExecl(string filePath, DataTable dt) { if (File.Exists(filePath)) { File.Delete(filePath); } IWorkbook wk = new XSSFWorkbook(); ; //建立一個名稱爲data的表
ISheet tb = wk.CreateSheet("data"); //表頭
IRow row1 = tb.CreateRow(0); int k = 0; foreach (DataColumn dc in dt.Columns) { ICell cell1 = row1.CreateCell(k); cell1.SetCellValue(getChinaName(dc.ColumnName)); k = k + 1; } //表體
for (int i = 0; i < dt.Rows.Count; i++) { IRow row = tb.CreateRow(i + 1); for (int j = 0; j < dt.Columns.Count; j++) { if (j == 3) { ICell cell = row.CreateCell(j); string value = dt.Rows[i][j].ToString(); cell.SetCellValue(tranSchoolType(value)); } else { ICell cell = row.CreateCell(j); string value = dt.Rows[i][j].ToString(); cell.SetCellValue(value); } } } string uploadPath = HttpContext.Current.Server.MapPath(filePath); //打開一個xls文件,若是沒有則自行建立 //若是存在myxls.xls文件則在建立是不要打開該文件!
using (FileStream fs = File.OpenWrite(uploadPath)) { //向打開的這個xls文件中寫入mySheet表並保存。
wk.Write(fs); } }
是用excel2003仍是excel2007能夠用下面這個方法:excel
static IWorkbook isExcelType(string filePath) { IWorkbook wk = null; FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); if (filePath.IndexOf(".xlsx") > 0) // 2007版本
wk = new XSSFWorkbook(fs); else if (filePath.IndexOf(".xls") > 0) // 2003版本
wk = new HSSFWorkbook(fs); fs.Close(); return wk; }
從excel讀取數據:code
List<Dictionary<string, string>> readExcel(string filePath) { IWorkbook wk = null; wk = isExcelType(filePath); ISheet sheet = wk.GetSheetAt(0); List<string> names = new List<string>();//LastRowNum 是當前表的總行數
for (int j = 1; j <= sheet.LastRowNum; j++)
{ for (int j = 1; j <= sheet.LastRowNum; j++)
{blog
//讀取當前行數據
IRow row = sheet.GetRow(j);
if (row != null)
{
//LastCellNum 是當前行的總列數
for (int k = 0; k <= row.LastCellNum; k++)
{get
//當前表格
ICell cell = row.GetCell(k);
if (cell != null)
{
string name = cell.ToString();
names.Add(name);
}
}
}
}
List<Dictionary<string, string>> lists = new List<Dictionary<string, string>>();
return lists;
}string
好了,以上就簡單的完成導入導出了!it