使用像素單位設置 EXCEL 列寬或行高

在導出 Excel 的時候, 常常要須要給列設置寬度或給行設置高度, 在使用 NPOI 或 EppPlus 等組件進行操做的時候, 列寬和行高的單位都不是像素, 好像是英寸,具體是啥也說不清。this

日常在使用單位時, 已經習慣使用像素了, 因此但願在 EXCEL 裏設置列寬或行高時也使用像素。spa

 

以前在使用 Aspose.Cells 時, 發現這個組件有個 SetRowHeightPixel 方法, 能夠使用像素設置行高, 因而使用反編譯看了一下實現原理:code

 

private static float GetDpiX()
{
    try
    {
        using (Bitmap image = new Bitmap(1, 1))
        {
            using (Graphics graphics = Graphics.FromImage(image))
            {
                return graphics.DpiX;
            }
        }
    }
    catch
    {
        return 72;
    }
}


public void SetRowHeightPixel(int row, int pixels)
{
    double height = (double)((float)pixels * 72f / (float)GetDpiX());
    this.SetRowHeight(row, height);
}
相關文章
相關標籤/搜索