如何使用"保存文件"对话框导出网格视图Excel数据,而无需使用数据源



我真的不知道大家是否可以理解我的问题,但我会尽量说清楚,我有一个 DataGrid 视图,我不使用实体框架来填充它的数据只是我显示了来自我的数据库的直接数据来填充它,如下所示:

private void load()
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["UR2k_CS.Properties.Settings.StoreConnectionString"].ConnectionString);
SqlDataAdapter data = new SqlDataAdapter("Select * FROM [dbo].[missingItems]", con);
DataTable table = new DataTable();
data.Fill(table);
dataGridView1.Rows.Clear();
foreach (DataRow item in table.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item["RFID"].ToString();
dataGridView1.Rows[n].Cells[1].Value = item["name"].ToString();
dataGridView1.Rows[n].Cells[2].Value = item["model"].ToString();
dataGridView1.Rows[n].Cells[3].Value = item["category"].ToString();
dataGridView1.Rows[n].Cells[4].Value = item["prix"].ToString();
dataGridView1.Rows[n].Cells[5].Value = item["ref"].ToString();
}

我想使用保存文件对话框将其数据导出到.csv文件中(以使用户选择保存位置(,我在网上找到了该代码:

private void btnExportToExcel_Click(object sender, EventArgs e)
{
var dia = new System.Windows.Forms.SaveFileDialog();
dia.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
dia.Filter = "Excel Worksheets (*.xlsx)|*.xlsx|xls file (*.xls)|*.xls|All files (*.*)|*.*";
if(dia.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
{
DataTable data = null;// use the DataSource of the DataGridView here
var excel = new OfficeOpenXml.ExcelPackage();
var ws = excel.Workbook.Worksheets.Add("worksheet-name");
// you can also use LoadFromCollection with an `IEnumerable<SomeType>`
ws.Cells["A1"].LoadFromDataTable(data, true, OfficeOpenXml.Table.TableStyles.Light1);
ws.Cells[ws.Dimension.Address.ToString()].AutoFitColumns();
using(var file = File.Create(dia.FileName))
excel.SaveAs(file);
}
}

但是正如你看到的伙计们,我没有数据源,所以如何用我的网格视图数据填充它。

你有一个数据表...

SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["UR2k_CS.Properties.Settings.StoreConnectionString"].ConnectionString);
SqlDataAdapter data = new SqlDataAdapter("Select * FROM [dbo].[missingItems]", con);
DataTable table = new DataTable();
data.Fill(table);

为什么不只使用此表导出到 excel? 如果您的 datable 与要导出的列不匹配,您仍然需要管理列映射...

最新更新