在上面的代码中,我需要传递“excelFilename”?
在Azure中,我建议将excel文件保存到Azure Blob存储。根据你的代码,你可以创建一个新的,在内存流中托管的excel。在将数据写入此Excel文件后,我们可以将内存流上传到Blob存储。以下代码供您参考。
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;
}
}
要使用上方法,只需要将文件名放在第二个参数中即可。
CreateExcelDocument(ds, "abc.xlsx");
之后,名为abc.xlsx的文件将在您的Blob存储的excelfilecontainer中创建。您可以从Azure存储资源管理器或Azure存储客户端库查看或下载它。
而且如果excel工作表或数据集具有多于一个。那么如何添加新表单?
我们还可以将blob数据读取到内存流中。然后我们可以打开一个基于这个流的SpreadsheetDocument。添加新工作表后。我们需要将此流保存回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))
{
}
}
谢谢,如果Excel表单或数据集有多个。那么如何添加新表单? – Abhi
我根据您的评论修改了我的回复。如果您需要更多关于如何使用SpreadsheetDocument的帮助,我建议您使用[openxml-sdk]标签发布一个新问题。你会在那里得到更多的专业帮助。如果您的问题得到解决,我建议您将有用的答复标记为答案。已标记的线程将很容易搜索到。它将帮助遇到类似问题的其他社区成员。 – Amor