简体   繁体   中英

How to export data to excel with checkListBox

I have a windows form application with a check list box. So far I am able to bind my data to my checkListBox and have created a excel file using Microsoft.Office.Interop.Excel library. I have my code below. This part of the code work fine. However you can see that my code is linked with employeeCheckListBox which displayed employee's Nick Name to excel file if any of this of checkbox is checked. This code work fine if I only select one item from the checkListBox. But it doesn't work if I select 2 items from the checkListBox. I think the problem is at this line from my code string f_Name = dr.GetString(1) , it does read the rest of the f_name from my database.

It show something like this in the excel.

出来吧

What I really want is this 渴望出来

Here is my database table 数据库表

I do know how to do this, help will be appreciated

Here is my code to create the Excel file

    private void exportToExcel() {
            object missing = Type.Missing;
            Excel.Application xlApp = new Excel.Application();

            xlApp.Visible = false;


             Excel.Workbook xlwb = xlApp.Workbooks.Add(missing);

      //first worksheet
         Excel.Worksheet xlEmployeeDetail = xlwb.ActiveSheet as Excel.Worksheet;

    //Cell name 
    xlEmployeeDetail.Cells[1, 1] = "Teacher Id";
    xlEmployeeDetail.Cells[1, 2] = "First Name";
    xlEmployeeDetail.Cells[1, 3] = "Last Name";
    xlEmployeeDetail.Cells[1, 4] = "Nick Name";

    //Read the data from the SQL database and store its according value to excel
    while (dr.Read()) {

          //f_Name is reading from column 5 from my db
        string f_Name = dr.GetString(1);
        string l_Name = dr.GetString(2);

        for (int i = 0; i < employeeCheckListBox.CheckedItems.Count; i++) {
            string s = (string) employeeCheckListBox.Items[i];

            xlEmployeeDetail.Cells[2 + i, 4] = s;
            xlEmployeeDetail.Cells[2 + i, 2] = f_Name;
        }
    }

    //Delete rows if there are any empty row
    var LastRow = xlEmployeeDetail.UsedRange.Rows.Count;
    LastRow = LastRow + xlEmployeeDetail.UsedRange.Row - 1;

    int c = 0;

    for (c = 1; c <= LastRow; c++) {
        if (xlApp.WorksheetFunction.CountA(xlEmployeeDetail.Rows[c]) == 0)
        (xlEmployeeDetail.Rows[c] as Microsoft.Office.Interop.Excel.Range).Delete();
    }
}
}

Instead of writing to a separate line for each database row, your inner loop overwrites the rows with the last data read.

To write your table's data, you only need to write the following code:

int i=1;
while (dr.Read()) {
    i++;
    //f_Name is reading from column 5 from my db
    string f_Name = dr.GetString(1);
    string l_Name = dr.GetString(2);

    xlEmployeeDetail.Cells[i, 4] = l_Name;
    xlEmployeeDetail.Cells[i, 2] = f_Name;
}

This assumes that the data reader returns only the records that should actually be exported. If not, the SQL statement used to load the data should be modified to load only the data to export

The way the original code was written, for each database row, the inner loop would write over the same rows and columns.

A better solution would be use a library like EPPlus to export data directly to an Excel file without using Interop or Excel at all. EPPlus has the LoadFromDataTable and LoadFromCollection convenience methods that allow you to export data from a DataTable or object collection directly to a sheet, eg:

using (ExcelPackage pck = new ExcelPackage())
{
    //Create the worksheet
    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");

    //Load the datatable into the sheet, starting from cell A1. 
    //Print the column names on row 1
    ws.Cells["A1"].LoadFromDataTable(someTable, true);

    pck.SaveAs(new FileInfo(@"c:\PathTo\File.xlsx"))
}

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