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.
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();
}
}
}