一般情况下写入Excel是通过Worksheet.get_Range("A1).Value="" 的方式给单元格一个一个的赋值,如果数据量不大还是可以满足要求的。但是如果数据量过大这种方式操作会很慢。
目前发现直接数组赋值的方式会减少单元格赋值的次数从而加速写入的速度
string[,] arr = GetArr(sourceColleciotn, dics);
sheet.Range[sheet.Cells[startRow, keys.FirstOrDefault()], sheet.Cells[endRow, keys.LastOrDefault()]].Value = arr;
网上还有一种使用NPOI 来操作Excel说是会更加稳定和快速,也可以通过将数据转换为字符串(enter 换行tab换列)然后复制到粘贴板,通过粘贴板粘贴到Excel中,有兴趣的可以试试
在指定位置写入一个数组,如果你只知道起始和结束的列名(英文字母例如A,AA,BAA),就需要我们把拼音转换为数字位置才能获取到二维数组的列数
如果我们把A对应1把Z对应26 把AA对应27.。。。。这样我们通过结束列名和结束列名转换为数字位置然后相减就可以获取到列数。
/// <summary>
相应的我们可能需要通过数组列位置获取对应的Excel列拼音名称/// 根据Excel列拼音获取列数 /// </summary> /// <param name="colName"></param> /// <returns></returns> public static int GetExcelColNum(string colName) { char[] chars = colName.ToCharArray(); int txt1 = 0; for (int i = 0; i < chars.Length; i++) { txt1 = txt1 + (int)Math.Round(Math.Pow(26, i), 0); } for (int i = 0; i < chars.Length; i++) { txt1 = txt1 + ((int)Math.Round(Math.Pow(26, chars.Length - i - 1), 0)) * (chars[i] - 65); } return txt1; }
/// <summary>
/// 根据列指标位置获取列拼音字母 /// </summary> /// <param name="z"></param> /// <returns></returns> public string GetExcelColStr(int z) { int length = 0; for (int i = 1; i < 100; i++) { int bj = 0; for (int k = 0; k < i; k++) { bj = bj + (int)Math.Round(Math.Pow(26, k), 0); } for (int k = 0; k < i; k++) { bj = bj + ((int)Math.Round(Math.Pow(26, i - k - 1), 0)) * 25; } if (bj >= z) { length = i; break; } } for (int i = 0; i < length; i++) { z = z - (int)Math.Round(Math.Pow(26, i), 0); } string str = string.Empty; for (int i = 1; i <= length; i++) { int charV = (int)(z / (int)Math.Round(Math.Pow(26, length - i), 0)) + 65; char a = (char)charV; str = str + a.ToString(); z = z - (int)(Math.Round(Math.Pow(26, length - i), 0)) * (charV - 65); } return str; }