C# WinForms导出SQL数据到Excel时数组索引越界问题求助
问题解决思路
错误根源
出现"Index was outside the bounds of the array"的原因是:你用递增的stt1作为数组arr1的索引,但arr1固定只有4个元素(索引范围0-3),而stt1会随着循环次数持续增加,当循环到第5次及以后时,stt1的值会超过数组的最大索引,触发越界错误。
修正方案
根据你的需求,分两种常见场景给出修正代码:
场景1:只要当前行某固定列(比如第一个列col2)的值≥2,整行设置为红色加粗
int stt1 = 0; float temp = 2.0f; row = 6; foreach (var element in datalist) { stt1++; row++; dynamic[] arr1 = { element.col2, element.col3, element.col4, element.col5 }; Range rowData = ws.get_Range("C" + row, "F" + row); rowData.Font.Size = 11; rowData.Font.Name = "Times New Roman"; rowData.Value2 = arr1; // 直接取当前行的目标列元素,这里取第一个元素对应col2(Excel的C列) float currentValue = Convert.ToSingle(arr1[0]); if (currentValue >= temp) { rowData.Font.Bold = true; rowData.Font.Color = ColorTranslator.ToOle(Color.Red); } }
场景2:逐个检查单元格,仅值≥2的单元格设置为红色加粗
int stt1 = 0; float temp = 2.0f; row = 6; foreach (var element in datalist) { stt1++; row++; dynamic[] arr1 = { element.col2, element.col3, element.col4, element.col5 }; Range rowData = ws.get_Range("C" + row, "F" + row); rowData.Font.Size = 11; rowData.Font.Name = "Times New Roman"; rowData.Value2 = arr1; // 遍历当前行的每个单元格,检查对应值 for (int i = 0; i < arr1.Length; i++) { float currentValue = Convert.ToSingle(arr1[i]); if (currentValue >= temp) { // 获取当前行的第i+1个单元格(Excel单元格索引从1开始) Range targetCell = rowData.Cells[1, i + 1]; targetCell.Font.Bold = true; targetCell.Font.Color = ColorTranslator.ToOle(Color.Red); } } }
内容的提问来源于stack exchange,提问作者Anh Lee
相关产品推荐
相关产品推荐

