I am using standard library
using Excel = Microsoft.Office.Interop.Excel;
And this is how I create Excel, just small part of code:
//Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; object misValue = System.Reflection.Missing.Value; Excel._Application xlApp = new Excel.Application(); xlWorkBook = xlApp.Workbooks.Add(misValue); xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); //add data xlWorkSheet.Cells[1, 1] = ""; xlWorkSheet.Cells[1, 2] = "Student1"; xlWorkSheet.Cells[1, 3] = "Student2"; xlWorkSheet.Cells[1, 4] = "Student3";
The problem is that sometimes size of cell can be smaller that text`s size. I tried this one:
Excel.Range chartRange; chartRange.EntireColumn.ColumnWidth = 31.43;
It works fine, but I need to set this property for each column separately. How I can I do that?
Resize columns Select a column or a range of columns. On the Home tab, select Format > Column Width (or Column Height). Type the column width and select OK.
You can also AutoFit the width for several columns at the same time. Simply select the columns you want to AutoFit, then select the AutoFit Column Width command from the Format drop-down menu on the Home tab. This method can also be used for row height.
I normally do this in VB and its easier because Excel records macros in VB. So I normally go to Excel and save the macro I want to do.
So that's what I did now and I got this code:
Columns("E:E").ColumnWidth = 17.29; Range("E3").Interior.Pattern = xlSolid; Range("E3").Interior.PatternColorIndex = xlAutomatic; Range("E3").Interior.Color = 65535; Range("E3").Interior.TintAndShade = 0; Range("E3").Interior.PatternTintAndShade = 0;
I think you can do something like this:
xlWorkSheet.Columns[5].ColumnWidth = 18;
For your last question what you need to do is loop trough the columns you want to set their width:
for (int i = 1; i <= 10; i++) // this will apply it from col 1 to 10 { xlWorkSheet.Columns[i].ColumnWidth = 18; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With