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?
This question is related to
c#
excel
office-interop
I did it this way:
var xlApp = new Excel.Application();
var xlWorkBook = xlApp.Workbooks.Add(System.Reflection.Missing.Value);
var xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.Item[1];
xlWorkSheet.Columns.AutoFit();
With this way, columns always fit to text width inside cells.
Hope it helps to someone!
This link explains how to apply a cell style to a range of cells: http://msdn.microsoft.com/en-us/library/f1hh9fza.aspx
See this snippet:
Microsoft.Office.Tools.Excel.NamedRange rangeStyles =
this.Controls.AddNamedRange(this.Range["A1"], "rangeStyles");
rangeStyles.Value2 = "'Style Test";
rangeStyles.Style = "NewStyle";
rangeStyles.Columns.AutoFit();
Excel ColumnWidth from dataGridView:
foreach (DataGridViewColumn co in dataGridView1.Columns)
{ worksheet.Columns[co.Index + 1].ColumnWidth = co.Width/8; }
See this snippet: (C#)
private Microsoft.Office.Interop.Excel.Application xla;
Workbook wb;
Worksheet ws;
Range rg;
..........
xla = new Microsoft.Office.Interop.Excel.Application();
wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
ws = (Worksheet)xla.ActiveSheet;
rg = (Range)ws.Cells[1, 2];
rg.ColumnWidth = 10;
rg.Value2 = "Frequency";
rg = (Range)ws.Cells[1, 3];
rg.ColumnWidth = 15;
rg.Value2 = "Impudence";
rg = (Range)ws.Cells[1, 4];
rg.ColumnWidth = 8;
rg.Value2 = "Phase";
I have change all columns width in my case as
worksheet.Columns[1].ColumnWidth = 7;
worksheet.Columns[2].ColumnWidth = 15;
worksheet.Columns[3].ColumnWidth = 15;
worksheet.Columns[4].ColumnWidth = 15;
worksheet.Columns[5].ColumnWidth = 18;
worksheet.Columns[6].ColumnWidth = 8;
worksheet.Columns[7].ColumnWidth = 13;
worksheet.Columns[8].ColumnWidth = 17;
worksheet.Columns[9].ColumnWidth = 17;
Note: Columns in worksheet start with 1 not from 0 as in Arrary.
Use this One
((Excel.Range)oSheet.Cells[1, 1]).EntireColumn.ColumnWidth = 10;
Source: Stackoverflow.com