Как выгрузить данные из программы в excel?

code: #csharp
using Excel = Microsoft.Office.Interop.Excel; 
 
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
 
            try
            {
                Excel.Application xlApp;
                Excel.Workbook xlWorkBook;
                Excel.Worksheet xlWorkSheet;
                Excel.Range range;              
                int rCnt = 0;
                int cCnt = 0;
                object misValue = System.Reflection.Missing.Value;
 
                xlApp = new Excel.ApplicationClass();
                xlWorkBook = xlApp.Workbooks.Open(Application.StartupPath + "\\csharp-Excel.xls", 0, false, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
                xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
 
                range = xlWorkSheet.UsedRange;
 
                for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
                {
                    for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
                    {
                        try
                        {
                            string temp = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2 + " ";
 
                            if (temp.StartsWith("#"))
                                xlWorkSheet.Cells[rCnt, cCnt] = "Заменили";
                        }
                        catch { }
                    }
                }
                xlWorkBook.SaveAs(Application.StartupPath + "\\csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                xlWorkBook.Close(true, misValue, misValue);
                xlApp.Quit();             
 
                releaseObject(xlWorkSheet);
                releaseObject(xlWorkBook);
                releaseObject(xlApp);
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }
 
        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }
 
    }
Поделиться:

Похожие статьи: