generateFromCsv static method
Parse CSV string (from LLM code block) into XLSX bytes.
First row is treated as header and styled bold. Numeric values are detected and stored as numbers (not strings).
Implementation
static Uint8List generateFromCsv({
required String csvContent,
String sheetName = 'Datos',
}) {
final workbook = Excel.createExcel();
final sheet = workbook[sheetName];
// Remove default Sheet1 if we're using a custom name
if (sheetName != 'Sheet1') {
workbook.delete('Sheet1');
}
final lines = csvContent.trim().split('\n');
for (var row = 0; row < lines.length; row++) {
final cells = _parseCsvLine(lines[row]);
for (var col = 0; col < cells.length; col++) {
final value = cells[col].trim();
final cell = sheet.cell(
CellIndex.indexByColumnRow(columnIndex: col, rowIndex: row),
);
// Detect numeric values
final intVal = int.tryParse(value.replaceAll(',', ''));
final doubleVal = intVal == null
? double.tryParse(value.replaceAll(',', ''))
: null;
if (intVal != null) {
cell.value = IntCellValue(intVal);
} else if (doubleVal != null) {
cell.value = DoubleCellValue(doubleVal);
} else {
cell.value = TextCellValue(value);
}
// Bold header row
if (row == 0) {
cell.cellStyle = CellStyle(bold: true);
}
}
}
return Uint8List.fromList(workbook.encode()!);
}