在實際的開發應用中,數據庫導入導出是經常遇到的問題,尤其是數據庫與Excel文件之間的導入導出,還存在數據類型不一致的問題。例如:數據庫的數字超長時會在Excel裡格式化成科學計數法的格式,或者記錄內容是數字和字符的混合內容會丟失內容等等。將Access數據庫的內容直接導入到Excel則可以避免這些問題。
下面例子就是實現這個功能,例子中的數據庫使用《ASP.NET 2.0應用開發技術》一書中自帶的數據庫為例子。
另外,需要注意:Excel文件有諸多限制,在如果數據庫記錄內容很多,還要計算每次導出的數量和Sheet數目,另外,對Sheet名字相同的監測也省略了,需要的讀者請根據情況自行添加上去。結合存儲過程的分頁功能實現起來比較好。
C#:
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional //EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
string sql;
string connstr = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|ASPNET20Book.mdb;Persist Security Info=True";
System.Data.OleDb.OleDbConnection cn = new System.Data.OleDb.OleDbConnection(connstr);
System.Data.OleDb.OleDbCommand cmd;
cn.Open();
//先得到記錄數目:
sql = "select Count(*) From Paging";
cmd = new System.Data.OleDb.OleDbCommand(sql, cn);
int RecordCount = (int)cmd.ExecuteScalar();
// TODO:計算Sheet數目,進行記錄分段, 將不同的數據段導入到不同的Sheet(Sheet數目不知道有沒有限制:())
// TODO:文件名,Sheet名字的存在檢測略
//每個Sheet只能最多保存65536條記錄。
sql = @"select top 65535 * into [Excel 8.0;database=" + Server.MapPath(".") + @"ASPNET20Book.xls].[Sheet1] from Paging";
cmd = new System.Data.OleDb.OleDbCommand(sql, cn);
cmd.ExecuteNonQuery();
cn.Close();
cn.Dispose();
cn = null;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>直接將Access數據庫導入到Excel文件</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="到處數據">
</form>
</body>
</html>
VB.NET:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim sql As String
Dim connstr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|ASPNET20Book.mdb;Persist Security Info=True"
Dim cn As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection(connstr)
Dim cmd As System.Data.OleDb.OleDbCommand
cn.Open
sql = "select Count(*) From Paging"
cmd = New System.Data.OleDb.OleDbCommand(sql, cn)
Dim RecordCount As Integer = CType(cmd.ExecuteScalar, Integer)
sql = "select top 65535 * into [Excel 8.0;database=" + Server.MapPath(".") + "ASPNET20Book.xls].[Sheet1] from Paging"
cmd = New System.Data.OleDb.OleDbCommand(sql, cn)
cmd.ExecuteNonQuery
cn.Close
cn.Dispose
cn = Nothing
End Sub