我正在使用 excel 包创建 Excel 文件。我的问题是无法将图像插入 Excel 文件。如何插入图像或任何类型的二进制数据?
我的 Excel 文件包含 4 列:
我开发了导出 Excel 文件的代码。
void startExportCategoriesExcel(List<ExportParams> ExportParams,
CustomerModel customerModel, String accountBase64, bool share) async {
if (ExportParams.isEmpty) {
showToast(Trans.noDataToExport.trans());
return;
}
try {
showLoadingProgressAlert();
final String sheetName = "Category-PAR-${Random().nextInt(10000)}";
final excel = Excel.createExcel();
excel.rename('Sheet1', sheetName);
final Sheet sheetObject = excel[sheetName];
List<List<dynamic>> excelExport = [];
// excelExport = [
// [customerModel.customerName,
// customerModel.phoneNo ?? '',
// ]
// ];
excelExport.add([
"#",
Trans.image.trans(),
Trans.name.trans(),
Trans.uom.trans(),
Trans.price.trans(),
Trans.barcode.trans(),
]);
int index = 0;
for (var element in ExportParams) {
index++;
// Load the image from the network using http package
img.Image? image;
try {
var response = await Dio().get(element.image,
options: Options(responseType: ResponseType.bytes));
if (response.statusCode != 200) {
logger('Failed to load image: ${response.statusCode}');
}
image = img.decodeImage(Uint8List.fromList(response.data));
} catch (e) {
image = null;
}
final barcodeImage = img.Image(width: 300, height: 50);
img.fill(barcodeImage, color: img.ColorRgb8(255, 255, 255));
drawBarcode(
barcodeImage,
Barcode.code128(),
element.barcode ?? "",
);
// var excelImage = ExcelImage(image);
excelExport.add([
"$index",
image != null
? image.buffer.asUint8List()
: image ?? '', //element.image,
element.name,
element.prices.isEmpty ? '-' : element.prices.first.uom,
element.prices.isEmpty ? '-' : element.prices.first.price,
barcodeImage.buffer.asUint8List(), //element.barcode ?? '',
]);
}
for (var element in excelExport) {
sheetObject.appendRow(element);
}
List<int>? data4 = excel.encode();
if (data4 == null) {
failedAlert(error: Trans.operationFalied.trans());
return;
}
Directory? downloadsDirectory;
if (kIsWeb != true) {
if (Platform.isAndroid) {
// downloadsDirectory = await DownloadsPath.downloadsDirectory();
downloadsDirectory = await getApplicationDocumentsDirectory();
} else {
downloadsDirectory = await getApplicationDocumentsDirectory();
}
if (downloadsDirectory == null) {
failedAlert(error: Trans.operationFalied.trans());
return;
}
final String path = downloadsDirectory.path;
final dir = await Directory(path).create(recursive: true);
final fullPath =
"${dir.path}/${Trans.priceList.trans()} ${DateTime.now().toString().split(".")[0].replaceAll(":", "-")}.xlsx";
File file = File((fullPath));
if (await file.exists()) {
await file.delete();
}
file
..createSync(recursive: true)
..writeAsBytesSync(data4);
Helper.i.pop();
Helper.i.pop();
if (!share) {
openFileAlert(path: fullPath);
} else {
Share.shareXFiles([XFile(fullPath)]);
}
} else {
MimeType type = MimeType.microsoftExcel;
await FileSaver.instance.saveFile(
name:
"${Trans.accountStatments.trans()} ${DateTime.now().toString().split(".")[0].replaceAll(":", "-")}",
bytes: Uint8List.fromList(data4),
ext: "xlsx",
mimeType: type);
Helper.i.pop();
Helper.i.pop();
}
} catch (e, c) {
recoredError(e, c);
logger(e);
Helper.i.pop();
Helper.i.pop();
Helper.i.pop();
failedAlert(error: Trans.operationFalied.trans());
}
}
Excel Package目前没有图像/视频添加功能。正如该软件包的开发人员所说,这是一个复杂且耗时的过程。 在这里您可以看到未解决的问题。
相反,我建议您使用这个包https://pub.dev/packages/syncfusion_flutter_xlsio。它提供图像添加功能。这是例子;
// Create a new Excel document.
final Workbook workbook = new Workbook();
//Accessing worksheet via index.
final Worksheet sheet = workbook.worksheets[0];
//Adding a picture
final List<int> bytes = File('image.png').readAsBytesSync();
final Picture picture = sheet.picutes.addStream(1, 1, bytes);
// Save the document.
final List<int> bytes = workbook.saveAsStream();
File('AddingImage.xlsx').writeAsBytes(bytes);
//Dispose the workbook.
workbook.dispose();
祝你好运。