01/10/2018, 12:24
Lỗi khi xuất excel trong winform
Em xuất excel trong winform bị lỗi này. Em ko hiểu ai sửa giúp em với ạ. System.ArgumentOutOfRangeException: ‘Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index’
code:
private void btnExport_Click(object sender, EventArgs e)
{
//Khởi tạo Excel
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
//Khởi tạo workbook
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
//Khởi tạo worksheet
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
app.Visible = true;
// Đổ dữ liệu vào Sheet
worksheet.Cells[1, 1] = "BẢNG ĐIỂM HỌC SINH";
worksheet.Cells[3, 1] = "STT";
worksheet.Cells[3, 2] = "Mã học sinh";
worksheet.Cells[3, 3] = "Mã môn";
worksheet.Cells[3, 4] = "Điểm miệng";
worksheet.Cells[3, 5] = "Điểm giữa kỳ";
worksheet.Cells[3, 6] = "Điểm cuối kỳ";
for (int i = 0; i < dgvBangDiem.RowCount - 1; i++) {
for (int j = 0; i < 5; j++) {
worksheet.Cells[i + 4, 1] = i + 1;
worksheet.Cells[i + 4, j + 2] = dgvBangDiem.Rows[i].Cells[j].Value;
}
}
}
Bài liên quan
sao lai co i o đây? mà em đọc error không hiểu ý error có ý gì ah?
System.ArgumentOutOfRangeException: ‘Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index’
Thực sự cái lỗi của bạn nó chả liên quan gì đến excel lẫn winforms cả. Đọc thông báo lỗi là phải tự hiểu vấn đề chứ.
Nên chuyển sang lệnh foreach hết nha bạn.
Tốt hơn là không dùng bất kì lệnh loop (for, while, do while) trong chương trình. Thay thế bằng các hàm forEach, filter, map, reduce.