C# EPPlus column width issue

T.Zacks 3,996 Reputation points
2021-03-13T15:15:41.37+00:00

I have set column width 0.94 but after excel generation getting lesser width. is it bug? can anyone help me how to set column width and after excel generation i should be able to see same column width.

this way i set column width

ws.Column(2).Width = Convert.ToDouble(0.94);

i also tried this one too but did not work. i follow this link https://stackoverflow.com/questions/9096176/how-to-set-xlsx-cell-width-with-epplus

ws.Column(2).SetTrueColumnWidth(0.94)

 public static void SetTrueColumnWidth(this ExcelColumn column, double width)
        {
            if (width < 1)
            {
                column.Width = (12 / 7) * width;
            }
            else
            {
                column.Width = width + (5 / 7);
            }

        }

please help me how to handle column width issue? thanks

Developer technologies C#
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 122.6K Reputation points
    2021-03-13T19:20:27.153+00:00

    Check if this function works differently:

    public static void SetTrueColumnWidth(this ExcelColumn column, double width)
    {
       if (width < 1)
       {
          column.Width = (12.0 / 7) * width;
       }
       else
       {
          column.Width = width + (5.0 / 7);
       }
    }
    
    1 person found this answer helpful.
    0 comments No comments

  2. Timon Yang-MSFT 9,606 Reputation points
    2021-03-15T02:40:52.067+00:00

    Viorel-1's suggestion is correct. The result of 5/7 is the int value of 0, and the result of 5.0/7 is the double value of 0.714285714285714, which is what you need.

    You can also use Microsoft.Office.Interop.Excel, and then simply set the column width regardless of these things.

               Application application = new Application();  
                Workbook wb =  application.Workbooks.Open(@"D:\test\excel\3.xlsx");  
                Worksheet ws = (Worksheet)wb.Worksheets[1];  
      
                ((Excel.Range)ws.Cells[2, 1]).EntireColumn.ColumnWidth = 0.95;  
      
                wb.Save();wb.Close();application.Quit();  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.