Hi shani1,
I have created a sample that full-fill your requirement by refering the below article.
C#
private void btnExport_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
string constr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
string query = "SELECT TOP 10 CustomerId,ContactName,City,Country FROM Customers GO SELECT TOP 5 EmployeeID,(FirstName + ' ' + LastName) EmployeeName,City,Country FROM Employees";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(ds);
ds.Tables[0].TableName = "Customers";
ds.Tables[1].TableName = "Employees";
}
}
}
XLWorkbook wb = new XLWorkbook();
for (int i = 0; i < ds.Tables.Count; i++)
{
wb.Worksheets.Add(ds.Tables[i], ds.Tables[i].TableName);
}
string filePath = "";
if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
filePath = folderBrowserDialog1.SelectedPath;
}
wb.SaveAs(filePath + "\\DataGridViewExport.xlsx");
}
Screenshot
