将选定的行datagridview导出为excel [英] Export selected rows datagridview to excel
问题描述
这里是我的代码导出整个datagridview到excel
private void GenerateExcel(DataTable table3,string excelSheetName)
{
string fileName =TestingofDSI;
// string currentDirectorypath =C:\testingdsi;
string currentDirectorypath = Environment.CurrentDirectory;
string finalFileNameWithPath = string.Empty;
fileName = string.Format({0} _ {1},fileName,DateTime.Now.ToString(dd-MM-yyyy));
finalFileNameWithPath = string.Format({0} \\ {1} .xlsx,currentDirectorypath,fileName);
var newFile = new FileInfo(finalFileNameWithPath);
使用(var package = new ExcelPackage(newFile))
{
ExcelWorksheet工作表= package.Workbook.Worksheets.Add(excelSheetName);
if(table!= null)
{
workheet.Cells [A1]。LoadFromDataTable(table3,true,OfficeOpenXml.Table .TableStyles.Medium2);
//worksheet.Cells[\"A1\"].LoadFromDataTable(table,true,TableStyles.None);
/ * package.Workbook.Properties.Title = @此代码是http://bytesofcode.hubpages.com上提供的教程的一部分;
package.Workbook.Properties.Author =代码字节;
package.Workbook.Properties.Subject = @在这里注册更多http://hubpages.com/_bytes/user/new/\";*/
包。保存();
MessageBox.Show(string.Format(文件名{0}成功生成,fileName)
,文件生成成功,MessageBoxButtons.OK,MessageBoxIcon.Information );
}
else
{
MessageBox.Show(请从数据库加载数据!);
}
}
}
//绑定数据的代码
private void loadButton_Click(object sender,EventArgs e)
{
GetData(select * from jacksonpc.product;);
dataGridView1.DataSource = bindingSource1;
}
private void GetData(string selectCommand)
{
try
{
//指定连接字符串。将一个
//给出的值替换为Northwind SQL Server样本
//数据库可用于系统的有效连接字符串。
String connectionString =datasource = localhost; port = 3306; username = root; password = 1234;
//根据指定的查询创建一个新的数据适配器。
dataAdapter = new MySqlDataAdapter(selectCommand,connectionString);
//创建一个命令构建器来生成基于selectCommand的SQL update,insert和
// delete命令。这些用于
//更新数据库。
MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(dataAdapter);
//填充一个新的数据表并绑定到BindingSource。
table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
/ * table2 = new DataTable();
table2.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table2)
bindingSource2.DataSource = table2;
//调整DataGridView列的大小以适应新加载的内容。* /
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
}
catch(MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
你可以在构造函数或 Form_Load
中更改 datagridview
SelectionMode
p>
dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
然后用户将能够选择您必须创建的打印方法的 CTRL
或 Shift
的帮助的多行一个 DataTable
与所选的行:
foreach(DataGridViewRow rowGridView1中的行) SelectedRows)
{
//创建具有相同列名称的数据表
//填充每个列,如row.Cells [1] .Value.ToString();
}
i have to come out with a program to export selected rows datagridview to excel with the respective headers. I have done exporting the whole datagridview to excel, but now i want to do it with just the selected row. How can i do it?
here's my codes for exporting the whole datagridview to excel
private void GenerateExcel(DataTable table3, string excelSheetName) {
string fileName = "TestingofDSI";
//string currentDirectorypath = "C:\testingdsi";
string currentDirectorypath = Environment.CurrentDirectory;
string finalFileNameWithPath = string.Empty;
fileName = string.Format("{0}_{1}", fileName, DateTime.Now.ToString("dd-MM-yyyy"));
finalFileNameWithPath = string.Format("{0}\\{1}.xlsx", currentDirectorypath, fileName);
var newFile = new FileInfo(finalFileNameWithPath);
using (var package = new ExcelPackage(newFile))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(excelSheetName);
if (table != null)
{
worksheet.Cells["A1"].LoadFromDataTable(table3, true, OfficeOpenXml.Table.TableStyles.Medium2);
//worksheet.Cells["A1"].LoadFromDataTable(table, true, TableStyles.None);
/* package.Workbook.Properties.Title = @"This code is part of tutorials available at http://bytesofcode.hubpages.com";
package.Workbook.Properties.Author = "Bytes Of Code";
package.Workbook.Properties.Subject = @"Register here for more http://hubpages.com/_bytes/user/new/";*/
package.Save();
MessageBox.Show(string.Format("File name '{0}' generated successfully.", fileName)
, "File generated successfully!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("please load data from database!");
}
}
}
//code for binding data
private void loadButton_Click(object sender, EventArgs e)
{
GetData(" select * from jacksonpc.product;");
dataGridView1.DataSource = bindingSource1;
}
private void GetData(string selectCommand)
{
try
{
// Specify a connection string. Replace the given value with a
// valid connection string for a Northwind SQL Server sample
// database accessible to your system.
String connectionString = "datasource=localhost;port=3306;username=root;password=1234";
// Create a new data adapter based on the specified query.
dataAdapter = new MySqlDataAdapter(selectCommand, connectionString);
// Create a command builder to generate SQL update, insert, and
// delete commands based on selectCommand. These are used to
// update the database.
MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(dataAdapter);
// Populate a new data table and bind it to the BindingSource.
table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
/* table2 = new DataTable();
table2.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table2);
bindingSource2.DataSource = table2;
// Resize the DataGridView columns to fit the newly loaded content.*/
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
You can change datagridview
SelectionMode
property in constructor or Form_Load
dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
Then user will able to select multiple rows which the help of CTRL
or Shift
on you print method you have to create a DataTable
with selected Rows:
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
//Create a DataTable with same column name
//fill each column like row.Cells[1].Value.ToString();
}
这篇关于将选定的行datagridview导出为excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!