我知道有很多关于此问题的主题,但是我的要求更加具体。我正在使用EF将记录选择到项目中,然后将其导出到Excel。我用过This snippet code。
让我解释一下我要做什么。给定下表(为简化起见,如代码中所示,该表要大一些):
Name | Content
A "Content1"
A "Content2"
A "Content3"
B "other content"
......
当我导出到excel时,我不希望A
在每个内容旁边出现3次,我只希望有一个“ A”(我能做到)并合并将3个单元格(如果可能的话,也要使其居中对齐)合为一个(不触摸Content
列)。
这是我的代码:
public IActionResult Index()
{
var knownCampaigns = _repository.getDataForExport();
//return View(result);
string sWebRootFolder = _hostingEnvironment.WebRootPath;
string sFileName = @"demo.xlsx";
string URL = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, sFileName);
FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
if (file.Exists)
{
file.Delete();
file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
}
using (ExcelPackage package = new ExcelPackage(file))
{
// add a new worksheet to the empty workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("CampaignMatches");
//First add the headers
worksheet.Cells[1, 2].Value = "Customer Name";
worksheet.Cells[1, 3].Value = "Guid";
worksheet.Cells[1, 4].Value = "Campaign Title";
worksheet.Cells[1, 5].Value = "Referrer Title";
worksheet.Cells[1, 6].Value = "Activity Date";
worksheet.Cells[1, 7].Value = "Is clicked?";
int counter = 2;
string oldGuid = "";
foreach (var campaign in knownCampaigns)
{
if (oldGuid == campaign.Guid || worksheet.Cells["C" + (counter - 1)].Value.ToString() == campaign.Guid)
{
oldGuid = campaign.Guid;
worksheet.Cells["A" + counter].Value = "";
worksheet.Cells["B" + counter].Value = "";
}
else
{
oldGuid = "";
worksheet.Cells["A" + counter].Value = campaign.customerName;
worksheet.Cells["B" + counter].Value = campaign.Guid;
}
worksheet.Cells["C" + counter].Value = campaign.campaignTitle;
worksheet.Cells["D" + counter].Value = campaign.reffererTitle;
worksheet.Cells["E" + counter].Value = campaign.activityDate;
worksheet.Cells["F" + counter].Value = campaign.is_clicked;
counter++;
}
package.Save(); //Save the workbook.
}
var result = PhysicalFile(Path.Combine(sWebRootFolder, sFileName), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
Response.Headers["Content-Disposition"] = new ContentDispositionHeaderValue("attachment")
{
FileName = file.Name
}.ToString();
return result;
}
现在,我的Customer Name
和Guid
列仅按预期出现一次,但是我不知道如何将这些单元合并到一个单元中。
当前输出图像:
[![在此处输入图片描述] [2]] [2]
所需输出的图像:
[![在此处输入图片描述] [3]] [3]
答案 0 :(得分:0)
看起来并不那么明显。看起来工作表上有一个Elements属性,您可以添加MergedCell的类型。 https://docs.microsoft.com/en-us/office/open-xml/how-to-merge-two-adjacent-cells-in-a-spreadsheet
答案 1 :(得分:0)
如果有人会遇到相同的问题,我已经设法使用Merge
属性解决了这个问题,我不得不提取开始列索引,行索引,结束行索引和结束列索引的位置。 / p>
var Wsc_Guid = worksheet.Cells[startRowIndex, guidIndex, startRowIndex + numOfSameRecords, guidIndex];//Select the correct cells for Guids
Wsc_Guid.Merge = true;