繁体   English   中英

如何在不使用数据源的情况下使用保存文件对话框导出网格视图 excel 数据

[英]how to export grid view excel data using save File Dialog whithout using datasource

我真的不知道你们是否能理解我的问题,但我会尽量说清楚,我有一个 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 文件(使用户 select 保存位置),我在网上找到了该代码:

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? 如果您的数据表与您要导出的列不匹配,您仍然需要管理列映射...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM