C#匯出資料表為Excel檔案
阿新 • • 發佈:2019-01-21
博文以匯出Access資料庫中的資料表為例,只要修改一下同樣可以用於SQL Server資料庫。
string filePath = "F:\\Book.xls"; string OleDbConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0;Data Source = .\\Data\\Student.accdb;Jet OLEDB:Database Password = 123456"; OleDbConnection cnn = new OleDbConnection(OleDbConnectionString); cnn.Open(); OleDbCommand cmd = new OleDbCommand("select count(*) from [Books]", cnn); int num = (int)(cmd.ExecuteScalar()); //如果資料項的個數大於一個sheet表的最大行數,則拆分儲存在多個sheet表中 if (num <= 65535) { // [Excel 8.0;database= excel名].[sheet名] 如果是新建sheet表不能加$,如果向sheet裡插入資料要加$ // Excel 2003的sheet表最大行數65536,最大列數256。因為列頭要佔據一行,所以最多儲存65535條資料 cmd = new OleDbCommand("select top 65535 ISBN as ISBN, Title as 書名, Author as 作者, RegisterTime as 登記時間 into [Excel 8.0;database=" + filePath + "].[書籍表] from Books order by RegisterTime desc", cnn); cmd.ExecuteNonQuery(); } else { int num2 = num, i = 1; while (num2 > 0) { cmd = new OleDbCommand("select top 65535 * into [Excel 8.0;database=" + filePath + "].[書籍表" + i + "] from (select top " + num2 + " ISBN as ISBN, Title as 書名, Author as 作者, RegisterTime as 登記時間 from Books order by RegisterTime) order by 登記時間 desc", cnn); cmd.ExecuteNonQuery(); num2 -= 65535; i++; } } cmd.Dispose(); cnn.Close(); cnn.Dispose();