[英]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.