gpt4 book ai didi

c# - 从 C# 行为不当在 Excel 中设置单元格样式

转载 作者:行者123 更新时间:2023-11-30 15:36:21 27 4
gpt4 key购买 nike

我的以下代码片段是一个函数,它接受字符串的矩形矩阵和写入 xls 文件的路径。它将矩阵的内容放入 Excel 工作表的单元格中,并根据内容应用一些格式:

public static void WriteXL(string[,] matrix, string path)
{
XL.Application app = new XL.Application();
XL.Workbook wbk = app.Workbooks.Add();
XL.Worksheet wsht = wbk.Worksheets.Add();

for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
int _i = i + 1;
int _j = j + 1;

if (matrix[i, 0] == "Day" || matrix[i, 0] == "Date")
{
wsht.Cells[_i, _j].Font.Bold = true;
wsht.Cells[_i, _j].Font.Italic = false;
wsht.Cells[_i, _j].Style.Font.Name = "Arial";
wsht.Cells[_i, _j].Style.Font.Size = 12;
wsht.Cells[_i, _j].Style.Interior.Color = NumberFromColor(Color.Yellow);
}
else if (j == 0)
{
wsht.Cells[_i, _j].Font.Bold = false;
wsht.Cells[_i, _j].Font.Italic = true;
wsht.Cells[_i, _j].Style.Font.Name = "Arial";
wsht.Cells[_i, _j].Style.Font.Size = 12;
wsht.Cells[_i, _j].Style.Interior.Color = NumberFromColor(Color.Beige);
}
else
{
wsht.Cells[_i, _j].Font.Bold = false;
wsht.Cells[_i, _j].Font.Italic = false;
wsht.Cells[_i, _j].Style.Font.Name = "Arial";
wsht.Cells[_i, _j].Style.Font.Size = 10;
wsht.Cells[_i, _j].Style.Interior.Color = NumberFromColor(Color.White);
}

wsht.Cells[_i, _j].Value = matrix[i, j];
}
}

wbk.SaveAs(path);
wbk.Close();
app.Quit();
app = null;

GC.Collect();
GC.WaitForFullGCComplete();
GC.WaitForPendingFinalizers();
}

因此,如果您可以想象,有些行以“Day”和“Date”开头,它们是分隔行的行,例如标题。这些行具有粗体和黄色背景。除了落在这些分隔行上的单元格外,最左边的列具有米色背景和斜体文本。其余单元格为白色背景的普通文本。

当我打开生成的 xls 文件时,这根本不是我所看到的。首先,整个工作表是白色的。其次,“Day”(位于“Date”之前)是粗体但大小不正确。

看起来最近使用的颜色应用于整个工作表,字体大小更改仅应用于下一个单元格,而不是我当前所在的单元格。

最佳答案

尝试删除 .Style 例如

wsht.Cells[_i, _j].Font.Name 

代替

wsht.Cells[_i, _j].Style.Font.Name 

您想要对单元格本身进行操作,而不是对其样式进行操作,因为工作表上共享该样式的任何其他单元格也会受到影响。

关于c# - 从 C# 行为不当在 Excel 中设置单元格样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13811186/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com