我想将Sitecore重定向链接导出为CSV文件。在功能区中创建一个按钮,以及项目中的代码引用页面。(见下文)
public class ExportRedirectsListCmd : Command
{
public override void Execute(CommandContext context)
{
var RedirectFolder = new SitecoreContext(GetContentDatabase()).GetItem<BaseCommon>(context.Items[0].ID.ToGuid(), context.Items[0].Language);
var lstLinkToRedirect = RedirectFolder.Children.OfType<LinkToLinkRedirect>();
var filename = "RedirectsOutput_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv";
var sb = new StringBuilder();
sb.AppendLine($"{"Redirecttype"},{"Sourcelink Url"}, {"Targetlink Url"}");
// collect all information
var allLines = (from item in lstLinkToRedirect
select new object[]
{
item.RedirectType,
item.SourceLink.Url,
item.TargetLink.Url
}).ToList();
// insert the content
allLines.ForEach(line =>
{
sb.AppendLine(string.Join(",", line));
});
// Alertbox just for test
// SheerResponse.Alert(sb.ToString());
// return;
}
}
代码收集StringBuilder
中的所有信息。通过测试警告框显示预期信息。
现在将StringBuilder
信息下载到浏览器。 HttpContext在Sitecore中不起作用。
答案 0 :(得分:0)
您需要将文件保存在临时文件夹中,然后使用 SheerResponse.Download() API下载CSV文件,我还没有对此进行测试,但这可能是您所需要的:
public override void Execute(CommandContext context)
{
var RedirectFolder = new SitecoreContext(GetContentDatabase()).GetItem<BaseCommon>(context.Items[0].ID.ToGuid(), context.Items[0].Language);
var lstLinkToRedirect = RedirectFolder.Children.OfType<LinkToLinkRedirect>();
var filename = "RedirectsOutput_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv";
var sb = new StringBuilder();
sb.AppendLine($"{"Redirecttype"},{"Sourcelink Url"}, {"Targetlink Url"}");
// collect all information
var allLines = (from item in lstLinkToRedirect
select new object[]
{
item.RedirectType,
item.SourceLink.Url,
item.TargetLink.Url
}).ToList();
// insert the content
allLines.ForEach(line =>
{
sb.AppendLine(string.Join(",", line));
});
string filePath = "/temp/" + filename;
using( TextWriter tw = new StreamWriter(filePath))
{
tw.WriteLine(sb.ToString());
tw.Close();
}
SheerResponse.Download(filePath);
}