尝试将大Excel文件读入DataTable时出现OutOfMemoryException

问题描述 投票:2回答:1

我正在使用SSIS包来清理和.Xlsx文件中的数据加载到SQL Server表。我还要在.Xlsx文件中突出显示包含错误数据的单元格,为此我必须根据列名和行ID(我在数据电子表格中)获取列和行索引。为此,我将第一个电子表格(Error_Sheet)中的每个列名称与我在第二个电子表格中添加的列的行进行比较,并对行执行相同操作,如果我具有相同的单元格值,则返回列和行索引我的数据电子表格,并根据该列和行索引突出显示单元格。该脚本工作正常,但在尝试从服务器运行它后,我得到了一个内存异常,也在我的工作站上,它之前工作正常。

我试图减少我从数据中获取数据的范围:AC1:AC10000AC1:AC100,它只在第一次编译后才起作用,但它仍然会再次抛出异常。

string strSQLErrorColumns = "Select * From [" + Error_Sheet + "AC1:AC100]";
OleDbConnection cn = new OleDbConnection(strCn);

OleDbDataAdapter objAdapterErrorColumns = new OleDbDataAdapter(strSQLErrorColumns, cn);
System.Data.DataSet dsErrorColumns = new DataSet();
objAdapterErrorColumns.Fill(dsErrorColumns, Error_Sheet);
System.Data.DataTable dtErrorColumns = dsErrorColumns.Tables[Error_Sheet];
dsErrorColumns.Dispose();
objAdapterErrorColumns.Dispose();

foreach (DataColumn ColumnData in dtDataColumns.Columns){
    ColumnDataCellsValue = dtDataColumns.Columns[iCntD].ColumnName.ToString();
    iCntE = 0;

    foreach (DataRow ColumnError in dtErrorColumns.Rows){
        ColumnErrorCellsValue = dtErrorColumns.Rows[iCntE].ItemArray[0].ToString();

        if (ColumnDataCellsValue.Equals(ColumnErrorCellsValue)){

            ColumnIndex = ColumnData.Table.Columns[ColumnDataCellsValue].Ordinal;
            iCntE = iCntE + 1;
            break;
            }
        }

        iCntD = iCntD + 1;
    }

ColumnIndexHCell = ColumnIndex + 1;          
RowIndexHCell = RowIndex + 2;

Range rng = xlSheets.Cells[RowIndexHCell, ColumnIndexHCell] as Excel.Range;
rng.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);

有没有其他方法可以在DataTable中加载数据以获取列和行索引,而无需使用大量内存或使用Excel.Range.Cell而不是使用数据集和DataTable来获取xlsx文件中的Cell值,列和行索引?

我没有显示整个代码,因为它很长。如果需要更多信息,请随时通知我。

c# excel ssis etl script-task
1个回答
2
投票

当尝试从具有大量行的Excel读取数据时,最好按块读取数据(在OleDbDataAdapter中,您可以使用分页选项来实现)。

int result = 1;
int intPagingIndex = 0;
int intPagingInterval = 1000;

while (result > 0){

    result = daGetDataFromSheet.Fill(dsErrorColumns,intPagingIndex, intPagingInterval , Error_Sheet);
    System.Data.DataTable dtErrorColumns = dsErrorColumns.Tables[Error_Sheet];

    //Implement your logic here

    intPagingIndex += intPagingInterval ;

}

这将防止OutOfMemory异常。而且不再需要指定像AC1:AC10000这样的范围

参考

© www.soinside.com 2019 - 2024. All rights reserved.