How do I export data from my C# console application to Excel using Microsoft.Office.Interop dll?
问题:
回答1:
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
回答2:
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
Update
You go to this link for your solution with dataset
http://itsrashid.wordpress.com/2007/05/14/export-dataset-to-excel-in-c/
http://www.codeproject.com/KB/office/ExcelDataTable.aspx
Hope this may help you