3

我拥有的以下代码片段是一个函数,它接受字符串的矩形矩阵和写入 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”之前)是粗体但大小错误。

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

4

1 回答 1

4

Try dropping the .Style eg

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

instead of

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

You want to operate on the cell itself, not on its Style, since any other cells on the sheet which share that Style will also be affected.

于 2012-12-11T00:17:22.957 回答