[英]Save a datatable to excel sheet in vb.net winform application
一年前,我看到一个漂亮的简单代码,它获取数据表并将其保存在excel文件中。
诀窍是使用Web库(带有http的东西),我几乎可以肯定它是一个流。
我发现很多代码都有响应,但我不能让它在win-form环境中工作。 还有一个单元格细胞代码 - 不感兴趣 - 慢。
我想将它粘贴为范围或接近的东西。
谢谢
有许多组件库可以提供这种功能。
但是,您可能最简单地将数据输出为CSV文件并将其加载到Excel中。
我喜欢做的是将数据表放在一个网格中,允许用户进行排序和过滤。 然后他们可以使用剪贴板复制/粘贴到Excel。
Private Sub mnuCopy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuCopy.Click
If dgvDisplaySet.GetClipboardContent Is Nothing Then
MsgBox("Nothing selected to copy to clipboard.")
Else
Clipboard.SetDataObject(dgvDisplaySet.GetClipboardContent)
End If
End Sub
特别感谢周杰伦
我建议的旧代码是:
至少下次它会在这里等我;)
private void cmdSaveToExcel_Click(object sender, EventArgs e)
{
saveFileDialog1.Filter = "Excel (*.xls)|*.xls";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
txtPath.Text = saveFileDialog1.FileName;
}
// create the DataGrid and perform the databinding
System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid();
grid.HeaderStyle.Font.Bold = true;
if (connDBs != null && rtxtCode.Text != "")
{
DataTable dt;
dt = connDBs.userQuery(rtxtCode.Text); // getting a table with one column of the databases names
//grdData.DataSource = dt;
grid.DataSource = dt;
// grid.DataMember = data.Stats.TableName;
grid.DataBind();
// render the DataGrid control to a file
using (StreamWriter sw = new StreamWriter(txtPath.Text))
{
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
grid.RenderControl(hw);
}
}
MessageBox.Show("The excel file was created successfully");
}
else
{
MessageBox.Show("Missing connection or query");
}
}
您需要将数据表转换为ADO记录集,然后可以使用Range对象的CopyFromRecordset方法。 请参阅http://www.codeproject.com/KB/database/DataTableToRecordset.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.