[]
        
(Showing Draft Content)

Measure Digital Width

If you want to get or set column width by pixels, the result may appear different in GcExcel and Excel as both of them store column width by characters. To overcome this issue, GcExcel supports measuring digital width in order to calculate the accurate pixel value of a single digit.

GcExcel provides IGraphicsInfo interface in its API which can be implemented to know the accurate pixel value of a single digit. The GetDigitWidth method in IGraphicsInfo interface measures the text (or characters) based on different font attributes like font family, font size, font style etc. GcExcel API also supports GUI frameworks, such as WPF and Windows Forms.

Refer to the following example code which calculates the pixel value and exports the column width correctly in Excel.

class FakeGraphicsInfo : IGraphicsInfo
{
    public double Width { get; set; }
    public int GetDigitWidthCount { get; set; }
    public double GetDigitWidth(TextFormatInfo textFormat)
    {
        GetDigitWidthCount++;
        return Width;
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    var workbook = new Workbook();
    var theme = new Theme("custom");
    theme.ThemeFontScheme.Major[FontLanguageIndex.Latin].Name = "宋体";
    theme.ThemeFontScheme.Minor[FontLanguageIndex.Latin].Name = "宋体";
    workbook.Theme = theme;
    var sheet = workbook.ActiveSheet;
    var fakeGraphicsInfo = new FakeGraphicsInfo { Width = 8 };
    workbook.GraphicsInfo = fakeGraphicsInfo;
    sheet.StandardWidthInPixel = 20;
    sheet.Columns[0].ColumnWidthInPixel = 20;
    sheet.Range[1, 1].Value = "abc";
    workbook.Save("ColumnWidth.xlsx");
}

Note: Please note below points:

  • The above sample requires WinForms application to build and run.

  • The result of GetDigitWidth method is environment-dependent. Sometimes, it returns different results when running on different computers.