如何使用Microsoft.Office.Interop dll将数据从C#控制台应用程序导出到Excel?
Add a using statement like this:
using Excel = Microsoft.Office.Interop.Excel;
Then define a variable that will enable you to work with Excel documents and workbooks:
Excel.Application xlApp = new Excel.Application();
Create a function that will write from your DataSet into an Excel document (This is from one of my Windows applications button_click function, but I think you will be able to make the necessary adjustments):
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
DataGridViewRow red = dataGridView1.Rows[i];
for (int j = 0; j < red.Cells.Count-2; j++)
{
if (j != 0)
{
xlApp.Cells[i + 1, j + 1] = "'" + Convert.ToString(red.Cells[j].Value);
}
else
{
xlApp.Cells[i + 1, j + 1] = Convert.ToString(red.Cells[j].Value);
}
}
}
xlApp.AutoCorrect.ReplaceText = false;
saveFileDialog1.DefaultExt = ".xls";
saveFileDialog1.FileName = textBox2.Text;
saveFileDialog1.InitialDirectory = "Desktop";
saveFileDialog1.ShowDialog();
try
{
xlApp.ActiveWorkbook.SaveCopyAs(FileName);
}
catch
{
MessageBox.Show("Warning");
}
ImeDatoteke = "";
xlApp.Quit();
As you see, I use DataGridView to display the data that I want to write into the Excel file, but since DataGridView uses DataSets I dont think you will have to much problems to adjust this code
You can get many Excel tutorials for c sharp available on internet
Refer to this link http://csharp.net-informations.com/excel/csharp-excel-tutorial.htm
You go to this link for your solution with dataset
Hope this may help you
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.