我操作的是2007個2010版本的excel
首先是讀取
/// <summary>
/// 讀取xls\xlsx格式的Excel文件的方法
/// </summary>
/// <param name="path">待讀取Excel的全路徑</param>
/// <returns></returns>
private DataTable ReaderExcelToTable(string path)
{
//連接字符串
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
// Office 07及以上版本 不能出現多餘的空格 而且分號注意
using (OleDbConnection conn = new OleDbConnection(connString))
{
conn.Open();
//DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
// new object[] { null, null, null, "Table" }); //得到所有sheet的名字
string danXuanTiName = "sheet1";
string sql = string.Format("select * from [{0}]", danXuanTiName + "$"); //查詢字符串
OleDbDataAdapter dta = new OleDbDataAdapter(sql, connString);
DataSet set = new DataSet();
dta.Fill(set);
return set.Tables[0];
}
}
寫入excel
private void TableOutExcel(DataTable dt)
{
//指定要創建副本文件的路徑和Name
string filePath = Server.MapPath("/_Layouts/" + Guid.NewGuid().ToString() + ".xlsx");
//根據現存模板文件創建副本
File.Copy(Server.MapPath("/_Layouts/QuestionDemo.xlsx"), filePath);
//使用OleDb連接副本
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=YES';");
using (conn)
{
conn.Open();
foreach (DataRow row in dt.Rows)
{
OleDbCommand comd = new OleDbCommand("INSERT INTO [單選題$]([試題內容],[試題選項],[正確答案],[試題等級]) VALUES(@Question,@Option,@RAnser,@Drg)", conn);
comd.Parameters.AddWithValue("@Question", row[0].ToString());
comd.Parameters.AddWithValue("@Option", row[1].ToString());
comd.Parameters.AddWithValue("@RAnser", row[2].ToString());
comd.Parameters.AddWithValue("@Drg", row[3].ToString());
comd.ExecuteNonQuery();
}
}
// 輸出副本的二進制字節流
Response.ContentType = "application/ms-excel";
Response.AppendHeader("Content-Disposition", "attachment;filename=Question.xlsx");
Response.BinaryWrite(File.ReadAllBytes(filePath));
// 刪除副本
File.Delete(filePath);
}
這個方法的做法是,先copy服務器上的一個模板,然後根據模板生成一個excel,然後添加數據,最後輸出excel,讓用戶下載