0

i have created function to save data from datagridview to excel file.

Function to save :

 try
        {
            Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
            Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
            app.Visible = true;
            worksheet = workbook.Sheets["Sheet1"];
            worksheet = workbook.ActiveSheet;
            worksheet.Name = "Records";

            try
            {
                for (int i = 0; i < dataGridView2.Columns.Count; i++)
                {
                    worksheet.Cells[1, i + 1] = dataGridView2.Columns[i].HeaderText;
                }
                for (int i = 0; i < dataGridView2.Rows.Count; i++)
                {
                    for (int j = 0; j < dataGridView2.Columns.Count; j++)
                    {
                        if (dataGridView2.Rows[i].Cells[j].Value != null)
                        {
                            worksheet.Cells[i + 2, j + 1] = dataGridView2.Rows[i].Cells[j].Value.ToString();
                        }
                        else
                        {
                            worksheet.Cells[i + 2, j + 1] = "";
                        }
                    }
                }

                //Getting the location and file name of the excel to save from user. 
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
                saveDialog.FilterIndex = 2;

                if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    workbook.SaveAs(saveDialog.FileName);
                    MessageBox.Show("Export Successful", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            finally
            {
                app.Quit();
                workbook = null;
                worksheet = null;
            }
        }
        catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); }

And it works good on my computer with version : enter image description here

I try to run this on my second computer where is installed :

enter image description here

What i need to change in code to works with both versions? I'm looking example that will do the same but works on every office installation. Btw when i try to run on second computer i have this error : enter image description here

2 Answers 2

1

This isn't an answer directly to why your code throws that error. But as an alternative approach that works for me, could be worth trying? I used 'ClosedXML' package from Nuget... There are probably other options out there too like 'yob's reply, that I'm sure would also work fine.

using ClosedXML.Excel;

Then to save data:

        SaveFileDialog saveFile1 = new SaveFileDialog();
        saveFile1.Filter = "Excel file|*.xlsx";
        saveFile1.Title = "save results as Excel spreadsheet";
        saveFile1.FileName = title + " -" + DateTime.Now.ToString("yyyyMMdd") + ".xlsx";
        if (saveFile1.ShowDialog() == DialogResult.OK)
        {
            var wb = new XLWorkbook();
            var ws = wb.Worksheets.Add(data, title);
            wb.SaveAs(saveFile1.FileName);
        }

'data' is a datatable, so you would need to convert the datagridview to datatable first. As I said, not an answer to your existing code, but a possible alternative that works for me :) Good luck.

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah it works good , but now how can i load it into datagridview again from file?
Have a read of aspsnippets.com/Articles/…. Theres an example in there for loading back into your program from excel file using ClosedXML
0

if you're not bound to use MS Office components, then I'd suggest to use EPPlus library instead.

string saveasFileName = .....

using (var package = new ExcelPackage())
{
    using (var worksheet = package.Workbook.Worksheets.Add("Records"))
    {
        worksheet.Cells[1, 1].Value = "Records from dataGridView2:";
        worksheet.Cells[1, 1].Style.Font.Bold = true;
        //  column headers
        for (int i = 0; i < dataGridView2.Columns.Count; i++)
        {
            worksheet.Cells[2, i + 1].Value = dataGridView2.Columns[i].HeaderText;
        }
        // actual data
        for (int i = 0; i < dataGridView2.Rows.Count; i++)
        {
            for (int j = 0; j < dataGridView2.Columns.Count; j++)
            {
                //  ... populate worksheet ...
                worksheet.Cells[i + 3, j + 1].Value = dataGridView2.Rows[i].Cells[j].Value?.ToString()??"";
            }
        }
        // save
        package.SaveAs(saveasFileName);
    }
}

I have an example at https://github.com/siccolo/EppPlus_CreateExcel/blob/master/Excel.cs

@Adamszsz - if you need to open an excel file and load into gridview, then you can use oledb connection, for example: - open excel file .xls:

...
var excelconnection = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
var table = "[Sheet1$]"
//  using System.Data.OleDb
var excel = new OleDbDataAdapter("SELECT * FROM " + table, excelconnection);
var exceldata = new DataTable();
excel.Fill(exceldata);
...

while for excel file .xlsx use Net.SourceForge.Koogra.Excel2007.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.