Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EPPLUS AutoFit cells

how can i set autosize on my cells, based on the max length of one input.

using (rng = workSheet.Cells["A1:G1"])
{
    rng.Style.Font.Bold = true;
    rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
    rng.Style.Fill.BackgroundColor.SetColor(Color.DarkBlue);
    rng.Style.Font.Color.SetColor(Color.White);

}

using (ExcelRange col = workSheet.Cells[2, 6, 7, 7])
{
    col.Style.Numberformat.Format = "yyyy-mm-dd HH:mm";
    col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;

}

for (int i = 1; i <= a; i++)
{
    workSheet.Cells["A1"].Value = "RU_ID";
    workSheet.Cells["B1"].Value = "COR_REQ_ID";
    workSheet.Cells["C1"].Value = "RU_NAME";
    workSheet.Cells["D1"].Value = "PARENT_RU_NAME";
    workSheet.Cells["E1"].Value = "ADJUSTMENT_STATE";
    workSheet.Cells["F1"].Value = "COR_START";
    workSheet.Cells["G1"].Value = "COR_END";
}
...

rng.AutoFitColumns();
string path = @"D:\excel\test.xlsx";
Stream stream = File.Create(path);
excel.SaveAs(stream);
stream.Close();
byte[] data = File.ReadAllBytes(path);

}

The only thing that AutoFitColumn is doing is to bring the cell to the size of the header, as if i have the header as "STH" and the inputs as "Something good", "something to increase cell size" than AutoFitColumn will set the size based on "STH" not "something to increase cell size". Thanks in advance for the help.

like image 578
Andrei Paul Avatar asked Apr 22 '16 12:04

Andrei Paul


People also ask

How do you AutoFit a column in Excel?

Select the column or columns that you want to change. On the Home tab, in the Cells group, click Format. Under Cell Size, click AutoFit Column Width. Note: To quickly autofit all columns on the worksheet, click the Select All button, and then double-click any boundary between two column headings.

How do I merge cells in Epplus?

If you want to merge cells dynamically, you can also use: worksheet. Cells[FromRow, FromColumn, ToRow, ToColumn].


1 Answers

Look at your lines:

using (rng = workSheet.Cells["A1:G1"])
...
rng.AutoFitColumns();

Notice you are call AutoFitColumns on the range of of your headers A1:G1 so EPPlus is using only those cells to determine the width of the columns.

Just do this instead:

workSheet.Cells.AutoFitColumns();

since Cells in Epplus only contain cells with actual values so there is no real concern over efficiency.

like image 67
Ernie S Avatar answered Sep 24 '22 20:09

Ernie S