Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

programmatically excel cells to be auto fit width & height

when i convert datatable to .csv my excel sheets are generated as below: enter image description here

and tried like below:

sw.Write(string.Format("=\"{0}\"", drow[i].ToString()));

then my excel sheets were like:

enter image description here

note that cells have =" " characters;

i'm trying to do like auto fit width & height of each cells programmatically. How?

like image 459
Sankar M Avatar asked Oct 03 '12 14:10

Sankar M


People also ask

How do I make Excel Cells expand width to fit text automatically?

Change the column width to automatically fit the contents (auto fit) 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.

How do you AutoFit Cells in Excel using VBScript?

To autofit Excel columns using scripting in Power Automate: Use the Set variable action to create a new variable containing the path of the Excel file you want to manipulate. In this example, the variable is named ExcelFile. Deploy the Run VBScript action and populate the following code.

How can you AutoFit the width of column?

In "Table Tools" click the [Layout] tab > locate the "Cell Size" group and choose from of the following options: To fit the columns to the text (or page margins if cells are empty), click [AutoFit] > select "AutoFit Contents." To fit the table to the text, click [AutoFit] > select "AutoFit Window."


2 Answers

Try getting the range and then do Autofit

Range.Rows.AutoFit();
Range.Columns.AutoFit();
like image 174
Jayant Varshney Avatar answered Oct 20 '22 00:10

Jayant Varshney


This questions just helped me to solve part of a problem. I had to copy the data to a secondary, auxiliary sheet, then send it to the datagrid, but when I did, it would display in the datagrid the sequence of ######### for some of my data that was larger than the field itself. So I used **sheets.UsedRange.Columns.AutoFit();** to solve the problem every time a new column is created. Where sheets is my variable who received the **Microsoft.Office.Interop.Excel.Worksheet**.

Thank you guys very much.

like image 20
Khamul Avatar answered Oct 20 '22 00:10

Khamul