Olá, estou com um problema para exportar um grande volume de dados para o excel.
O problema é o tempo de execução, já tentei de várias formas com Microsoft.Office.Interop.Excel, DocumentFormat.OpenXml, oledb e outros meios, com o oledb não consigo adicionar valores com mais de 255 caracteres nas células então não finalizei
de fato com oledb.
O Arquivo excel possui várias planilhas entre elas umas 2 ou 3 planilhas com 1 milhão de registros, mas ultimamente não consigo gerar com esse número de registros pois consome muita memória e assim eu quebro a planilha com 300 mil registros.
Pra adicionar esses 300 mil registros o script demora 70s, mas há casos onde vou ter 4 planilhas com 300 mil registros cada, fora as outras planilhas com um número menor de registros.
Resumindo meu script demora mais de 5 min pra realizar esse exportação mas esse tempo não é viável tenho que diminuir esse tempo pra pelo menos uns 2 min.
Agradeço a quem puder me ajudar, já estou há algumas semanas quebrando a cabeça com isso.
Segue o meu último script:
public static void InsertWorksheet(this DataTable table, string docName)
{
// Open the document for editing.
using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
{
// Add a blank WorksheetPart.
WorksheetPart newWorksheetPart = spreadSheet.WorkbookPart.AddNewPart<WorksheetPart>();
var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
newWorksheetPart.Worksheet = new Worksheet(sheetData);
Sheets sheets = spreadSheet.WorkbookPart.Workbook.GetFirstChild<Sheets>();
string relationshipId = spreadSheet.WorkbookPart.GetIdOfPart(newWorksheetPart);
uint sheetId = 1;
if (sheets.Elements<Sheet>().Count() > 0)
{
sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
}
string sheetName = table.TableName;
Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
sheets.Append(sheet);
DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
foreach (System.Data.DataColumn column in table.Columns)
{
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);
headerRow.AppendChild(cell);
}
sheetData.AppendChild(headerRow);
//percorrendo as linhas do datatable e inserindo na sheet
foreach (System.Data.DataRow dsrow in table.Rows)
{
DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
foreach (DataColumn col in table.Columns)
{
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue((string)dsrow[col.ColumnName]);
newRow.AppendChild(cell);
}
sheetData.AppendChild(newRow);
}
}
}