Alex Gordon
Alex Gordon

Reputation: 60731

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?

Upvotes: 5

Views: 6058

Answers (3)

Antonio Bakula
Antonio Bakula

Reputation: 20693

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

Upvotes: 3

Uwe Keim
Uwe Keim

Reputation: 40736

You also could use a third-party tool like e.g. Aspose.Cells to create the Excel file.

I've used this in a lot of projects successfully. It provides the auto-fit function that you require.

Upvotes: 0

Tony Dallimore
Tony Dallimore

Reputation: 12413

In Excel VBA, you can achieve the effect you seek with Rng.Columns.AutoFit. I believe the C# equivalent is Rng.Columns.AutoFit();.

However, I agree with Diodeus, you will have to fix your html first.

Upvotes: 1

Related Questions