我的要求是导出一个包含 5 列的空白 Excel 工作表,其中所有行的第三列作为下拉列表,以便用户可以使用此工作表根据需要修改数据。我正在使用 C# 导出文件。
我已经在研究它,但目前,它只在特定单元格中创建一个下拉列表,但我想将第一列的所有行作为下拉列表。
我正在使用 gembox 电子表格创建 Excel 文件。
下面是我正在使用的代码:
SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");
ExcelFile ef = new ExcelFile();
ExcelWorksheet ws = ef.Worksheets.Add("Journal Entry Format");
ws.Columns[0].Width = 30 * 256;
ws.Columns[1].Width = 30 * 256;
ws.Columns[2].Width = 30 * 256;
ws.Columns[3].Width = 30 * 256;
ws.Columns[4].Width = 30 * 256;
ws.Columns[5].Width = 30 * 256;
ws.Columns[6].Width = 30 * 256;
CellStyle tmpStyle2 = new CellStyle();
tmpStyle2.HorizontalAlignment = HorizontalAlignmentStyle.Center;
tmpStyle2.VerticalAlignment = VerticalAlignmentStyle.Center;
tmpStyle2.FillPattern.SetSolid(System.Drawing.Color.Yellow);
ws.Cells.GetSubrangeAbsolute(0, 0, 1, 5).Style = tmpStyle2;
ws.Cells[1, 0].Value = "Last";
ws.Cells.GetSubrangeAbsolute(1, 0, 1, 5).Merged = true;
CellStyle tmpStyle1 = new CellStyle();
tmpStyle1.HorizontalAlignment = HorizontalAlignmentStyle.Center;
tmpStyle1.VerticalAlignment = VerticalAlignmentStyle.Center;
tmpStyle1.FillPattern.SetSolid(System.Drawing.Color.Blue);
tmpStyle1.Font.Weight = ExcelFont.BoldWeight;
tmpStyle1.Font.Color = System.Drawing.Color.White;
tmpStyle1.WrapText = true;
ws.Cells[3, 0].Value = "Voucher Date";
ws.Cells[3, 1].Value = "Voucher No.";
ws.Cells[3, 2].Value = "Select Ledger";
ws.Cells[3, 3].Value = "Debit/Credit";
ws.Cells[3, 4].Value = "Amount";
ws.Cells[3, 5].Value = "Narration";
ws.Cells.GetSubrangeAbsolute(3, 0, 3, 5).Style = tmpStyle1;
var list = new List<string>();
foreach (var led in ledgers)
{
list.Add(led.AccountHead);
}
var flatList = string.Join(",", list.ToArray());
for (int i = 3; i < 100; ++i)
{
DataValidation dv = new DataValidation();
dv.InCellDropdown = true;
dv.InputMessage = "Select Ledger";
dv.Formula1 = flatList;
ws.DataValidations.Add(dv);
ws.Columns[2].Cells[i + 1].Value = dv.Formula1;
}
ws.PrintOptions.FitWorksheetWidthToPages = 1;
ef.Save(this.Response, "JournalEntry Format" + ".xlsx");
以下是将第三列单元格设置为下拉列表的方法:
var flatList = string.Join(",", list.ToArray());
DataValidation dv = new DataValidation(ws.Columns[2].Cells);
dv.Type = DataValidationType.List;
dv.InputMessage = "Select Ledger";
dv.Formula1 = flatList;
ws.DataValidations.Add(dv);
我不知道是否有人会读到这篇文章,但我找到了答案。您需要将参考数据插入其他位置,然后在公式中引用它。
清除电子表格上任何现有的数据过滤器也很重要,因为 gembox 不会覆盖它。
var hiddenSheet = template.Worksheets["hiddenSheet"];
var arr = list.ToArray();
for (int i = 0; i < arr).Length; i++)
{
hiddenSheet.Cells[i, 1].Value = arr[i];
}
var flatList = string.Join(",", arr);
DataValidation dv = new DataValidation(ws.Columns[2].Cells);
dv.Type = DataValidationType.List;
dv.InputMessage = "Select Ledger";
dv.Formula1 = $"=hiddenSheet!$Z$1:$Z${arr.Length}";
ws.DataValidations.Add(dv);