標籤:style io os ar for 檔案 資料 sp cti
平常編程中,我們經常遇到需要到處Excel表的地方,下面是小編的總結,希望對大家有用。
Scoresmr score = new Scoresmr(); //建立Scoresmr對象 DataSet ds = score.QueryScore(); //調用QueryScore方法查詢成績並將查詢結果放到DataSet資料集中 DataTable DT = ds.Tables[0]; //產生將要存放結果的Excel檔案的名稱 string NewFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"; //轉換為實體路徑 NewFileName = Server.MapPath("Temp/" + NewFileName); //根據模板正式產生該Excel檔案 File.Copy(Server.MapPath("../Modulemr.xls"), NewFileName, true); //建立指向該Excel檔案的資料庫連接 string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + NewFileName + ";Extended Properties='Excel 8.0;'"; OleDbConnection Conn = new OleDbConnection(strConn); //開啟串連,為操作該檔案做準備 Conn.Open(); OleDbCommand Cmd = new OleDbCommand("", Conn); foreach (DataRow DR in DT.Rows) { string XSqlString = "insert into [Sheet1$]"; XSqlString += "([使用者姓名],[試卷],[成績],[考試時間]) values("; XSqlString += "'" + DR["UserName"] + "',"; XSqlString += "'" + DR["PaperName"] + "',"; XSqlString += "'" + DR["Score"] + "',"; XSqlString += "'" + DR["ExamTime"] + "')"; Cmd.CommandText = XSqlString; Cmd.ExecuteNonQuery(); } //操作結束,關閉串連 Conn.Close(); //開啟要下載的檔案,並把該檔案存放在FileStream中 System.IO.FileStream Reader = System.IO.File.OpenRead(NewFileName); //檔案傳送的剩餘位元組數:初始值為檔案的總大小 long Length = Reader.Length; Response.Buffer = false; Response.AddHeader("Connection", "Keep-Alive"); Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode("學產生績.xls")); Response.AddHeader("Content-Length", Length.ToString()); byte[] Buffer = new Byte[10000];//存放欲發送資料的緩衝區 int ByteToRead;//每次實際讀取的位元組數 while (Length > 0) { //剩餘位元組數不為零,繼續傳送 if (Response.IsClientConnected) { //用戶端瀏覽器還開啟著,繼續傳送 ByteToRead = Reader.Read(Buffer, 0, 10000);//往緩衝區讀入資料 Response.OutputStream.Write(Buffer, 0, ByteToRead);//把緩衝區的資料寫入用戶端瀏覽器 Response.Flush();//立即寫入用戶端 Length -= ByteToRead;//剩餘位元組數減少 } else { //用戶端瀏覽器已經斷開,阻止繼續迴圈 Length = -1; } } //關閉該檔案 Reader.Close(); //刪除該Excel檔案 File.Delete(NewFileName);
C#中到處Excel表