Click here to Skip to main content
14,767,352 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have my codes below , when i try to run the codes only the first column in the excel that's fits. the other column where not, i want to see all of my column where automatically fits, hope you could help me guys !

What I have tried:

For k As Integer = 1 To DataGridView1.Columns.Count
xlWorkSheet.Cells(1, k) = DataGridView1.Columns(k - 1).HeaderText
xlWorkSheet.Cells(i + 2, j + 1) = DataGridView1(j,i).Value.ToString()

xlWorkSheet.Cells.RowHeight = 20
xlWorkSheet.Range("A1:F1").Columns.EntireColumn.AutoFit()
Posted
Updated 4-Apr-18 21:17pm
Comments
David O'Neil 18-Mar-18 23:33pm
   
Where is the end of your 'For' statement?

xlWorkSheet.Range(xlWorkSheet.Cells(i, 1), xlWorkSheet.Cells(i, 10)).ColumnWidth = AutoSize


This May Help You To auto fit Columns in Excel Sheet
   
Move this line outside the for..next loop and you'll get what you want.
xlWorkSheet.Range("A:F").Columns.AutoFit()
'or
'xlWorkSheet.Columns("A:F").AutoFit()


More at MSDN: Range.AutoFit Method (Excel)[^]
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900