我正在使用 EPPlus 从现有模板创建 excel 表。
我的代码上传到 azure blob 存储。Azure 数据工厂自定义活动使用它。
对于此活动,我需要使用 azure blob 中的模板 excel 文件。
我想提供模板文件的 URL。
var newFile = new FileInfo("Report_Template.xlsx");
有没有解决方案或替代方案?
因为这种情况太少见了,所以我没有从网络搜索中得到解决方案。
我正在使用 EPPlus 从现有模板创建 excel 表。
我的代码上传到 azure blob 存储。Azure 数据工厂自定义活动使用它。
对于此活动,我需要使用 azure blob 中的模板 excel 文件。
我想提供模板文件的 URL。
var newFile = new FileInfo("Report_Template.xlsx");
有没有解决方案或替代方案?
因为这种情况太少见了,所以我没有从网络搜索中得到解决方案。
昨天,当我想从 SharePoint 库加载 Excel 模板、更改数据并将更改作为新的 Excel 文件保存回 SharePoint 时,我偶然发现了这个问题。因此,这可能会回答基本问题:如何通过 url 而不是 FileInfo 打开。
我做了以下,它的工作原理:
public string CreateSheet()
{
string siteUrl = SPContext.Current.Site.Url;
string retval = string.Empty;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite sc = new SPSite(siteUrl))
{
using (SPWeb web = sc.OpenWeb())
{
SPFile spFile = web.GetFile("SiteCollectionDocuments/Template.xlsx");
Stream stream = spFile.OpenBinaryStream();
using (ExcelPackage p = new ExcelPackage(stream))
{
ExcelWorksheet sheetRoles = p.Workbook.Worksheets["Roles"];
sheetRoles.Cells[2, 1].Value = "Today: " + DateTime.Now.ToString("dd.MM.yyyy");
byte[] data = p.GetAsByteArray();
stream.Close();
web.AllowUnsafeUpdates = true;
SPDocumentLibrary lib = web.Lists.TryGetList("Site Collection Documents") as SPDocumentLibrary;
string fileName = "TheNewFileNameToUse-" + DateTime.Now.ToString("dd.MM.yyyy") + ".xlsx";
lib.RootFolder.Files.Add("SiteCollectionDocuments/" + fileName, data, true);
retval = siteUrl + "/_layouts/15/WopiFrame.aspx?sourcedoc=/SiteCollectionDocuments/" + fileName + "&action=default";
}
}
}
});
return retval;
}
如您所见,您可以从通过从某个 url 获取创建的流创建 ExcelPackage。即使这个答案迟到了,也可能对其他人有所帮助。
FileInfo 用于磁盘文件,而不是 URL。无论如何,您都不需要使用 EPPlus。正如Web 示例所示,您可以将包直接保存到流中:
ExcelPackage pck = new ExcelPackage();
var ws = pck.Workbook.Worksheets.Add("Sample1");
ws.Cells["A1"].Value = "Sample 1";
ws.Cells["A1"].Style.Font.Bold = true;
var shape = ws.Drawings.AddShape("Shape1", eShapeStyle.Rect);
shape.SetPosition(50, 200);
shape.SetSize(200, 100);
shape.Text = "Sample 1 saves to the Response.OutputStream";
pck.SaveAs(Response.OutputStream);
您可以使用类似的代码写入 blob 的流。您可以使用CloudBlockBlob.OpenWrite或等效的异步方法 OpenWriteAsync打开流以写入 blob :
ExcelPackage pck = new ExcelPackage();
var ws = pck.Workbook.Worksheets.Add("Sample1");
// Build the sheet then ...
var blockBlob = container.GetBlockBlobReference("somefile.xlsx");
using(var stream=blockBlob.OpenWrite())
{
pck.SaveAs(stream);
}
可以将 Azure 存储中的 blob 读取到内存流中,然后直接读取它。代码示例类似于:
var storageAccount = CloudStorageAccount.Parse("Connection_String");
string dataBlobPath = "path_to_blob.xlsx";
var dataBlobUri = new Uri(storageAccount.BlobEndpoint,dataBlobPath);
var sourceBlob = new CloudBlockBlob(dataBlobUri, storageAccount.Credentials);
int worksheets;
using (Stream str = new MemoryStream())
{
await sourceBlob.DownloadToStreamAsync(str);
using (ExcelPackage p = new ExcelPackage(str))
{
worksheets = p.Workbook.Worksheets.Count;
}
}