Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating an excel file and automatically expanding column widths

I have a regular html table:

<table>
<tr>hello</tr>
<tr>world</tr>
</table> 

and I am creating an XLS file out of it:

string randomname = @"C:\attachmentsfolder\"  + System.IO.Path.GetRandomFileName() + ".xls";
System.IO.File.WriteAllText( randomname, message);

When I open the XLS file generated, I need to MANUALLY expand the columns in order to see long data.

My question is: How can I generate this XLS file such that the columns are already sized properly?

like image 436
Alex Gordon Avatar asked Oct 08 '22 08:10

Alex Gordon


1 Answers

You could do that easily with EPPlus (Open Source .NET Excel 2007+ library), and you will have a valid excel file, here is the example code :

public static void FitAndSaveToExcel(FileInfo excelFile, string sheetName)
{
  ExcelPackage pack = new ExcelPackage();
  ExcelWorksheet ws = pack.Workbook.Worksheets.Add(sheetName);
  ws.Cells[1, 1].Value = "Some Long text that needs fitting!";
  ws.Cells[1, 2].Value = "Short one";
  ws.Column(1).AutoFit();
  pack.SaveAs(excelFile);
}
like image 78
Antonio Bakula Avatar answered Oct 15 '22 11:10

Antonio Bakula