所有,我有一个实用程序可以将 DataTables 导出到 Excel(到.xls和 .xlsx 文件类型)。DataTable
当我达到(从 SQL Server 中提取的)的列或行限制时,我想将其拆分DataTable
为子项,每个子项都遵守限制(对于 .xls 256 列和 65,536 行和 .xlsx 16,384 列和 1,048,576 行)。
到目前为止,我已经编写了以下方法来做我想做的事
public static List<DataTable> SplitDataTable(DataTable mother, int nColLimit)
{
List<int[]> rangeList = new List<int[]>();
int primaryCols = mother.Columns.Count;
int nSplitCount = Convert.ToInt32(primaryCols / nColLimit);
int max = -1;
// Get the child ranges.
int tmpSup = 0;
for (int splits = 0; splits < nSplitCount; splits++)
{
if (rangeList.Count == 0)
tmpSup = (splits + 1) * (nColLimit - 1);
else
tmpSup = rangeList[splits - 1][1] + nColLimit;
rangeList.Add(new int[2] { splits * nColLimit, tmpSup });
if (max < tmpSup)
max = tmpSup;
}
rangeList.Add(new int[2] { ++max, primaryCols });
// Build child DataTables.
List<DataTable> childList = new List<DataTable>();
int childIndex = 0;
foreach (int[] range in rangeList)
{
childList.Add(new DataTable());
for (int i = range[0]; i < range[1]; i++)
for (int j = 0; j < mother.Rows.Count; j++)
childList[childIndex].Rows[j][i] = mother.Rows[j][i];
childIndex++;
}
return childList;
}
但是,这会引发一条indexOutOfRangeException
消息“位置 0 处没有行。”。我很欣赏错误来自哪里,但是将完整列从 复制mother
到孩子的最佳方法是什么?
我也试过
List<DataTable> childList = new List<DataTable>();
int childIndex = 0;
foreach (int[] range in rangeList)
{
childList.Add(new DataTable());
foreach(DataRow row in mother.Rows)
{
DataRow tmpRow = childList[childIndex].NewRow();
for (int i = range[0]; i < range[1]; i++)
tmpRow[i + 1] = row[i + 1];
}
childIndex++;
}
这给出了相同的范围例外。
谢谢你的时间。
编辑:我是如何做这个短期的
foreach (int[] range in rangeList)
{
childList.Add(new DataTable());
string strSqlTmp =
String.Format("declare @columns varchar(max) " +
"select @columns = case when @columns is null " +
"then '' " +
"else @columns + ', ' " +
"end + name " +
"from sys.columns " +
"where object_id = object_id('{0}') and name in " +
"(SELECT COLUMN_NAME " +
"FROM [{1}].INFORMATION_SCHEMA.COLUMNS " +
"WHERE TABLE_NAME = N'{0}' " +
"AND ORDINAL_POSITION > {2} AND ORDINAL_POSITION < {3}) " +
"declare @query varchar(max) " +
"set @query = 'select ' + @columns + ' from {0}' " +
"exec (@query);
// Then get each DataTable from SQL Server and fill the child list...