請問各位大大
我在Unity製作一個WebGL檔想要使他匯出xlsx檔(Excel)
使用的是EPPlus套件
我的原始碼的函數如下
using System;
using System.Text;
using UnityEngine;
public void ConvertJsonToXlsxAndTriggerDownload(string jsonData)
{
var data = JsonConvert.DeserializeObject<VoltageData>(jsonData);
using (var package = new ExcelPackage())
{
var worksheet = package.Workbook.Worksheets.Add("Sheet1");
worksheet.Cells[1, 1].Value = "Date";
worksheet.Cells[1, 2].Value = "MeterID";
worksheet.Cells[1, 3].Value = "Hour";
worksheet.Cells[1, 4].Value = "Voltage";
int row = 2;
foreach (var record in data.Records)
{
string date = record.Date;
foreach (var meterVoltage in record.MeterVoltages)
{
string meterId = meterVoltage.MeterID;
if (meterVoltage.HourlyVoltages != null)
{
foreach (var hourlyVoltage in meterVoltage.HourlyVoltages)
{
worksheet.Cells[row, 1].Value = date;
worksheet.Cells[row, 2].Value = meterId;
worksheet.Cells[row, 3].Value = $"{hourlyVoltage.Hour}:00";
worksheet.Cells[row, 4].Value = hourlyVoltage.Voltage;
row++;
}
}
}
}
// Convert Excel file to Base64 string
byte[] fileData = package.GetAsByteArray();
string base64String = Convert.ToBase64String(fileData);
// JavaScript code to trigger download
string jsFunction = $@"
function triggerFileDownload(fileName, base64Data) {{
function base64ToBlob(base64, type = 'application/octet-stream') {{
const binaryString = atob(base64);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {{
bytes[i] = binaryString.charCodeAt(i);
}}
return new Blob([bytes], {{ type }});
}}
const blob = base64ToBlob(base64Data, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}}
triggerFileDownload('{fileName}', '{base64String}');
";
Application.ExternalEval(jsFunction);
}
Debug.Log("Excel file has been converted and download triggered.");
}
但是丟到Apache Server執行會出現下列錯誤如下
可以請問該如何解決嗎??
非常感謝!
錯誤不是跟你說了name
是null
!
你提供的程式,沒有任何name
的相關信息。
不過看你的JS,也沒有定義任何fileName
?