Search code examples
exceldatagridviewc++-clixls

C++\CLI datagridview export to excel .xls file


The errors I have: don't create excel file just add another Microsoft excel in background process and saveFileDialog crash when I try to change file location:

saveFileDialog1->InitialDirectory = "C:";
saveFileDialog1->Title = "Save as Excel File";
saveFileDialog1->FileName = "";
saveFileDialog1->Filter = "Excel Files(2003)|*.xls|Excel Files(2007)|*.xlsx";
if(saveFileDialog1>ShowDialog()==System::Windows::Forms::DialogResult::OK){
Microsoft::Office::Interop::Excel::Application^ ExcelApp = gcnew Microsoft::Office::Interop::Excel::ApplicationClass();
ExcelApp->Workbooks->Add(Type::Missing);

for (int i = 1; i < datagridview1->Columns->Count + 1;i++)
{
ExcelApp->Cells[1, i] = datagridview1->Columns[i - 1]->HeaderText;
}

for (int i = 0; i < datagridview1->Rows->Count; i++)
{
for (int j = 0; j < datagridview1->Columns->Count; j++)
                {
ExcelApp->Cells[i+2,j+1] = datagridview1->Rows[i]->Cells[j]->Value->ToString();
}
}

ExcelApp->ActiveWorkbook->SaveCopyAs(saveFileDialog1->FileName->ToString());
ExcelApp->ActiveWorkbook->Saved=true;
ExcelApp->Quit();

Solution

  • I had a similar problem once, the problem is in rows and cells writhing your datagridview1 into file. Code should look like this:

    saveFileDialog1->Title = "Save as Excel File";
    saveFileDialog1->FileName = "";
    saveFileDialog1->Filter = "Excel Files(2003)|*.xls|Excel Files(2007)|*.xlsx";
    if(saveFileDialog1>ShowDialog()==System::Windows::Forms::DialogResult::OK){
    Microsoft::Office::Interop::Excel::Application^ ExcelApp = gcnew Microsoft::Office::Interop::Excel::ApplicationClass();
    ExcelApp->Workbooks->Add(Type::Missing);
    
    for (int i = 1; i < datagridview1->Columns->Count + 1;i++)
    {
    ExcelApp->Cells[1, i] = datagridview1->Columns[i - 1]->HeaderText;
    }
    for (int i = 0; i < datagridview1->Rows->Count; i++)
    {
    for (int j = 0; j < datagridview1->Columns->Count; j++)
                {
    ExcelApp->Cells[i + 2, j + 1] = datagridview1->Rows[i]->Cells[j]->Value;
    safe_cast<Range^>(ExcelApp->Cells[i + 2, j + 1]);    }
    }
    ExcelApp->ActiveWorkbook->SaveCopyAs(saveFileDialog1->FileName->ToString());
    ExcelApp->ActiveWorkbook->Saved=true;
    ExcelApp->Quit();