C# – creating an excel file and automatically expanding column widths

c++excelhtmlwinforms

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?

Best Solution

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);
}