Quantcast
Channel: Active questions tagged excel - Stack Overflow
Viewing all articles
Browse latest Browse all 89329

DataGridViewS export to excell sheetS

$
0
0

I want to export all my DataGridViews in one Excell document. For every DataGridView there shoud be a own sheet in the Excell File.

But with my code i only recive the Error: System.Runtime.InteropServices.COMException: HRESULT: 0x800A03EC"

I think there is something wrong with my parameters.

        private void exportToExcellButton_Click(object sender, EventArgs e)
    {
        SaveFileDialog saveFileD = new SaveFileDialog();
        string fileName = truckListBox.SelectedItem.ToString() + "__" + DateTime.Now.ToShortDateString();
        saveFileD.InitialDirectory = @"C:/TML/";
        saveFileD.FileName = fileName;

        if (!Directory.Exists(@"C:/TML/"))

            Directory.CreateDirectory(@"C:/TML/");

        List<DataGridView> dataGridViews = getAllDataGridViews();

        Microsoft.Office.Interop.Excel.Application app;
        Microsoft.Office.Interop.Excel.Workbook book;
        Microsoft.Office.Interop.Excel.Worksheet sheet;

        app = new Excel.Application();
        app.Visible = true;
        book = app.Workbooks.Add(System.Reflection.Missing.Value);

        foreach (var grid in dataGridViews)
        {
          int count = book.Worksheets.Count;
          sheet = (Worksheet)book.Sheets.Add(Type.Missing, book.Worksheets[count], Type.Missing, Type.Missing);
            sheet.Name = grid.Name.ToString().Remove(0, 13);

            int cMin = 0, rMin = 0;
            int c = cMin, r = rMin;

            // Set Headers
            foreach (DataGridViewColumn column in grid.Columns)
            {
            //Here appears the Error: System.Runtime.InteropServices.COMException: HRESULT: 0x800A03EC"
                sheet.Cells[r, c] = column.HeaderText;
                c++;
            }

            sheet.Range[sheet.Cells[r, cMin], sheet.Cells[r, c]].Font.Bold = true;
            sheet.Range[sheet.Cells[r, cMin], sheet.Cells[r, c]].VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;

            // Set Rows
            foreach (DataGridViewRow row in grid.Rows)
            {
                r++;
                c = cMin;
                // Set Cells
                foreach (DataGridViewCell item in row.Cells)
                {
                    sheet.Cells[r, c++] = item.Value;
                }
            }
        }
        book.Save();
        book.Close();
        app.Quit();
    }

Spended allready days into it and cant get it work. Thx for your Help!

EDIT: Fixed one error to get to the new one.


Viewing all articles
Browse latest Browse all 89329

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>