gpt4 book ai didi

c# - 将数据集导出到 EXCEL

转载 作者:太空宇宙 更新时间:2023-11-03 14:22:23 24 4
gpt4 key购买 nike

我正在使用以下代码将字段从数据库表导出到 excel。我想要做的是能够编写一个 SQL 语句来从多个表中检索字段并将它们导出到 excel 中。此代码只允许我导出一个表。另外,如何显示保存提示对话框?示例代码将不胜感激 - 非常感谢!

protected void export_Click(object sender, EventArgs e)
{

string sql = null;
string data = null;
string path = save_as.Text;

int i = 0;
int j = 0;

Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;

xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

//connectionString = "data source=servername;initial catalog=databasename;user id=username;password=password;";
SqlConnection cnn = new SqlConnection(GetConnectionString());
cnn.Open();
sql = "SELECT Story, CreationDate FROM Story";
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
DataSet ds = new DataSet();
dscmd.Fill(ds);

for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
{
data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 1, j + 1] = data;
}
}

xlWorkBook.SaveAs(path+".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);

//MessageBox.Show("Excel file created , you can find the file c:\\csharp.net-informations.xls");
}

private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
//MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}

最佳答案

在 ASP.NET 环境中执行办公自动化是不安全的。相反,您应该生成一个 csv、html 表格或 xlsx 文件并将其发送给客户端。对于 xlsx,您可以使用 Office Open XML SDK 稍微简化一些事情。

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=c6e744e5-36e9-45f5-8d8c-331df206e0d0&displaylang=en

关于c# - 将数据集导出到 EXCEL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4980467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com