How to export datatable to excel in c# windows application
10,523
This line is one problem:
datatable.WriteXml("C:\\Users\\Downloads\\agent.xlsx" + time + " - " + time1 + " - " + time2 + " - " + day + " - " + month + "");
You wrote agent.xlsx
, but then added some other values at the end.
The second problem is like Lewis Hai already described in his answer, is that you're using WriteXml
method, which will write your data as XML.
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Author by
Admin
Updated on June 27, 2022Comments
-
Admin about 2 years
I found some code through googling that allows me to export a data table to excel file. i successfully export the file from database table and save it in my document My coding is:
using System; using System.Data.OleDb; using System.Windows.Forms; using MySql.Data.MySqlClient; using System.Data; namespace ImportFile { public partial class Form1 : Form { public Form1() { InitializeComponent(); } String connection = "SERVER=******;"DATABASE=dbd;"UID=root;"PASSWORD=pws;"Convert Zero Datetime = True"; private void BExport_Click(object sender, EventArgs e) { DateTime dat = DateTime.Now; int time = dat.Hour; int time1 = dat.Minute; int time2 = dat.Second; int month = dat.Month; int day = dat.Day; MySqlConnection connection1 = new MySqlConnection(connection); connection1.Open(); MySqlCommand command = new MySqlCommand ("SELECT * FROM TABLE_Name",connection1); MySqlDataAdapter dataadpter = new MySqlDataAdapter(command); DataTable datatable = new DataTable("TABLE_NAME"); dataadpter.Fill(datatable); datatable.WriteXml("C:\\Users\\Downloads\\agent.xlsx" + time + " - " + time1 + " - " + time2 + " - " + day + " - " + month + ""); MessageBox.Show("export data"); } } }
my problem is that when i download file(click import button)its not download an excel file its just an normal file.
how i download it as excel file . if any one know this.... help me
-
Albireo over 8 yearsThe main problem is
DataTable.WriteXml
, not the file name. -
roemel over 8 years@Albireo Oh, well. Thanks for the hint. I didn't notice he's writing Xml... Was a bit too busy with the filename... Thx