简体   繁体   中英

Save Headers from datagridview to excel? save as Excel 2007 format (.xlsx)?

I am trying to create a program whereby i import data from an excel file(.xlsx), make changes to it and then save it back to the excel file. I have a couple of issues im stuck with which i hope you could help me with :

  1. When i export the datagridview back to Excel, it misses out the headers, how can i get it to export these as well? Everything else exports fine.

  2. At the moment it seems i can only save the export as a .xls file, how can i save it as a .xlsx file. I have changed the filename to xlsx, it creates the file but i cant view it in excel because the format is incorrect.

  3. Finally as above i wanted to save it to the original Excel file where i imported to the datagridview, however i get an error saying the "cannot access ...../debug folder, it may be corrupt or read only".

The following is the code for importing the the Excel (.xlsx) data to the datagridview

public Form1()
    {
        InitializeComponent();

        // populate the dataGridView with the Excel File
        string connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;
                                               """, @"C:\Documents and Settings\User\Desktop\Visual Studio\GBstock\GBstock\bin\Debug\FORM TEST.xlsx");
        string query = String.Format("select * from [{0}$]", "Sheet1");
        OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString);
        DataSet dataSet = new DataSet();
        dataAdapter.Fill(dataSet);
        dataGridView1.DataSource = dataSet.Tables[0];

        // populates the comboBox (cbSuppList) with all column headers
        for (int i = 3; i < dataGridView1.Columns.Count; i++)
            {
                cbSuppList.Items.Add(dataGridView1.Columns[i].HeaderText);
            }
    }

The following is the "Save" code from datagridview to Excel, allbeit .xls format

private void btnSave_Click(object sender, EventArgs e)
    {
        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;

        xlApp = new Excel.Application();
        xlWorkBook = xlApp.Workbooks.Add(misValue);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        int i = 0;
        int j = 0;

        for (i = 0; i <= dataGridView1.Rows.Count - 1; i++)
        {
            for (j = 0; j <= dataGridView1.Columns.Count - 1; j++)
            {
                DataGridViewCell cell = dataGridView1[j, i];
                xlWorkSheet.Cells[i + 1, j + 1] = cell.Value;
            }
        }
        xlWorkBook.SaveAs("C:/Documents and Settings/User/Desktop/Visual Studio/GBstock/GBstock/bin/Debug/FORM TEST.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
        xlWorkBook.Close(true, misValue, misValue);
        xlApp.Quit();
    }
  1. You never use the HeaderText, like:
    dataGridView1.Columns[X].HeaderText Before your first for loop, you may loop the column (as your second for loop) using the previous line (with X the column's index). The basic idea:

    for (int index = 0; index <= dataGridView1.Columns.Count - 1; index ++)
    {
    //dataGridView1.Columns[index ].HeaderText
    }

  2. Before Office 2007, you can use your method.
    But, with Office 2007 and more, you have to use OpenXML
    You can see an example : http://msdn.microsoft.com/en-us/library/bb508943(v=office.12).aspx You also may find some ressources in code project .

  3. Have you disposed all ressources used?
    Also, if you write xls data to xslx file, it's not the correct format (as you see)... If your dataAdapter is not disposed , the file may be lock (you cannot overwrite it). But, it may be an other error (where do you have the exception? what is the exception's type?)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM