在上面的代码中,我需要传递“excelFilename”什么?
在 Azure 中,我建议将 excel 文件保存到 Azure Blob Storage。根据您的代码,您可以创建一个托管在内存流中的新 excel。将数据写入此excel文件后,我们可以将内存流上传到Blob Storage。下面的代码供您参考。
public static bool CreateExcelDocument(DataSet ds, string fileName)
{
try
{
MemoryStream ms = new MemoryStream();
using (SpreadsheetDocument document = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook))
{
WriteExcelFile(ds, document);
}
//You need to create a storage account and put your azure storage connection string in following place
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("put your azure storage connection string here");
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("excelfilecontainer");
container.CreateIfNotExists();
CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);
ms.Position = 0;
blockBlob.UploadFromStream(ms);
return true;
}
catch (Exception ex)
{
return false;
}
}
要使用upper 方法,只需将文件名放在第二个参数中即可。
CreateExcelDocument(ds, "abc.xlsx");
之后,将在 Blob 存储的 excelfilecontainer 中创建一个名为 abc.xlsx 的文件。您可以从 Azure 存储资源管理器或 Azure 存储客户端库查看或下载它。
如果 excel 工作表或数据集有多个。那么如何添加新工作表?
我们还可以将 blob 数据读取到内存流中。然后我们可以打开一个基于此流的电子表格文档。添加新工作表后。我们需要将此流保存回 Blob 存储。这是示例代码。
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("storage connection string");
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("excelfilecontainer");
// Retrieve reference to a blob named "myblob.txt"
CloudBlockBlob blockBlob = container.GetBlockBlobReference("abc.xlsx");
using (var memoryStream = new MemoryStream())
{
blockBlob.DownloadToStream(memoryStream);
memoryStream.Position = 0;
using (SpreadsheetDocument doc = SpreadsheetDocument.Open(memoryStream, false))
{
}
}