简体   繁体   中英

Importing data from DataGridView to existing Excel file using GemBox

I am fairly new to programming and GemBox. I found this code that inserts a data from a DataGridView to an existing Excel sheet with headers and footers. What happens with the code is it replaces the exisiting excel file totally and removes all the headers and footers. What I want to do is just insert the data starting from cell A:9 without removing the pre-existing data from other excel cells. Is there anyway to do this using GemBox?

private void replace_Click(object sender, EventArgs e)
        {
            var saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "XLSX files (*.xlsx)|*.xlsx";
            saveFileDialog.FilterIndex = 3;

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                var workbook = new ExcelFile();
                var worksheet = workbook.Worksheets.Add("Sheet1");

                var options = new ImportFromDataGridViewOptions();
                options.ColumnHeaders = false;
                options.StartRow = 8;       
                options.StartColumn = 0;

                DataGridViewConverter.ImportFromDataGridView(worksheet, this.dataGridView1, options);

                workbook.Save(saveFileDialog.FileName);
            }
        }

Any help would greatly be appreciated.

Use this to import the data from DataGridView to an existing Excel sheet:

private void replace_Click(object sender, EventArgs e)
{
    var saveFileDialog = new SaveFileDialog();
    saveFileDialog.Filter = "XLSX files (*.xlsx)|*.xlsx";

    if (saveFileDialog.ShowDialog() == DialogResult.OK)
    {
        var workbook = ExcelFile.Load("Path to your existing Excel file.");
        var worksheet = workbook.Worksheets.ActiveWorksheet;
        var options = new ImportFromDataGridViewOptions("A9");

        DataGridViewConverter.ImportFromDataGridView(worksheet, this.dataGridView1, options);
        workbook.Save(saveFileDialog.FileName);
    }
}

Note, this will import the data starting from cell A9 and replace any existing data that is inside the range where the import was done.

In other words, if you have an Excel file that already has some data in cells A9, B9, etc. they will end up being overridden.

If you don't want that, then insert empty rows to make room for DataGridView data, like this:

worksheet.Rows.InsertEmpty(8, this.dataGridView1.Rows.Count);

var options = new ImportFromDataGridViewOptions("A9");
DataGridViewConverter.ImportFromDataGridView(worksheet, this.dataGridView1, options);

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