如何使用Microsoft.Office.Interop dll将数据集导出到C#控制台应用程序中的excel [英] how to export dataset to excel in c# console application using Microsoft.Office.Interop dll
问题描述
如何使用Microsoft.Office.Interop dll将数据从C#控制台应用程序导出到Excel?
How do I export data from my C# console application to Excel using Microsoft.Office.Interop dll?
推荐答案
添加using语句,如下所示:
Add a using statement like this:
using Excel = Microsoft.Office.Interop.Excel;
然后定义一个变量,使您可以使用Excel文档和工作簿:
Then define a variable that will enable you to work with Excel documents and workbooks:
Excel.Application xlApp = new Excel.Application();
创建一个将从DataSet写入Excel文档的函数(这是我的Windows应用程序的button_click函数之一,但我认为您将能够进行必要的调整):
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();
如您所见,我使用DataGridView显示要写入Excel文件的数据,但是由于DataGridView使用数据集,所以我认为调整该代码不会有很多问题
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
这篇关于如何使用Microsoft.Office.Interop dll将数据集导出到C#控制台应用程序中的excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!