how to export dataset to excel in c# console application using Microsoft.Office.Interop dll

烂漫一生 提交于 2019-12-06 14:52:49

问题


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



来源:https://stackoverflow.com/questions/8818404/how-to-export-dataset-to-excel-in-c-sharp-console-application-using-microsoft-of

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!