C# .NET - Auto Fit the cells of Excel

Asked By Abhi Rana
27-Aug-08 03:07 AM

I want to auto fit the cells of excel

Example ##### is coming in cell, if we select all sheet and go to format > Cells > autofit it auto the selected range. I want this to do programmatically I am using this


                        ObjWorkSheet.Cells.AutoFit();
                        ObjWorkSheet.Rows.AutoFit();

This is giving range selection error, How to select range of whole sheet and make it autofit

 

reply  reply

27-Aug-08 03:12 AM
To adjust the column width, you can do the following:

Excel.Range xlEntireColumn = null;
Excel.Range xlRange = null;

while (reader.Read()) {
for (int i=0;i<numcols;i++) {
xlsheet.ActiveSheet.Cells[row,i+1] = reader.GetValue(i).ToString();

xlRange = xlSheet.ActiveSheet.Cells[row, i+1];
xlEntireColumn = xlRange.EntireColumn;
xlEntireColumn.AutoFit();
}

Hope this helps.

#### showig in case of datatype of column are mismatch  #### showig in case of datatype of column are mismatch

27-Aug-08 03:14 AM

So u should make sure the column datatype is same as u describe in code

if u set String type column for that column which contain ### value then this will comes true value,

Some type it showing Date type when the contain the timespan value and if u set less with of that column

so make sure these things for fill execl sheet

hope this solve yr problem

Setting a Column Width in Excel  Setting a Column Width in Excel

27-Aug-08 03:14 AM
public void SetColumnWidth(Worksheet ws, int col, int width)
{
((Range)ws.Cells[1, col]).EntireColumn.ColumnWidth = width;
}
// autofit to contents
public void AutoFitColumn(Worksheet ws, int col)
{
((Range)ws.Cells[1, col]).EntireColumn.AutoFit();
}
Go through this link hope u find some help:
http://www.c-sharpcorner.com/UploadFile/mgold/Query2Excel12032005011029AM/Query2Excel.aspx
Refer the Eggheadcafe's past post of it and Article  Refer the Eggheadcafe's past post of it and Article
27-Aug-08 03:15 AM

Refer the Eggheadcafe's past post of it and Article

Or

Refer this code


public void ExportToExcel()
        {
            Microsoft.Office.Interop.Excel.ApplicationClass excel = new ApplicationClass();
            excel.Visible = true;
            Workbook wBook = excel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
            Worksheet wSheet = (Worksheet)wBook.Worksheets[1];
            Range wRange;
 
            excel.Cells[2, 3] = "Schedule of Professional Tax";
            wRange = (Range)excel.Cells[2, 3];
            wRange.Font.Bold = true;
 
            excel.Cells[2,4] = "Month/Year:";
            wRange = (Range)excel.Cells[2, 4];
            wRange.Font.Bold = true;
            wRange.Columns.AutoFit();
 
            excel.Cells[2, 5] = dtpMonthYear.Text.ToString();
            if (cmbGrade.Text.Trim() != "")
            {
                excel.Cells[3, 4] = "Grade:";
                excel.Cells[3, 5] = cmbGrade.Text.Trim();
            }
 
            //Export Column Names
            excel.Cells[4, 1] = "S.No";
            wRange = (Range)excel.Cells[4, 1];
            wRange.Columns.Font.Bold = true;
            wRange.Columns.AutoFit();
 
            excel.Cells[4, 2] = "Emp.Code";
            wRange = (Range)excel.Cells[4, 2];
            wRange.Columns.Font.Bold = true;
            wRange.Columns.AutoFit();
 
            excel.Cells[4, 3] = "Name/Designation of person";
            wRange = (Range)excel.Cells[4, 3];
            wRange.Columns.Font.Bold = true;
            wRange.Columns.AutoFit();
 
            excel.Cells[4, 4] = "Amount";
            wRange = (Range)excel.Cells[4, 4];
            wRange.Columns.Font.Bold = true;           
 
            //Add Values
            double TotalAmt = 0;
            for (int i = 0; i < dgvPTDetails.Rows.Count; i++)
            {
                excel.Cells[6 + i, 1] = i + 1;
                excel.Cells[6 + i, 2] = dgvPTDetails.Rows[i].Cells[1].Value.ToString();
                excel.Cells[6 + i, 3] = dgvPTDetails.Rows[i].Cells[2].Value.ToString() + "/" + dgvPTDetails.Rows[i].Cells[3].Value.ToString();
                excel.Cells[6 + i, 4] = dgvPTDetails.Rows[i].Cells[4].Value.ToString();               
 
                //Calculate TotalAmount
                string Amt = "";
                Amt = dgvPTDetails.Rows[i].Cells[4].Value.ToString();
                if (Amt == "")
                { Amt = "0"; }
                TotalAmt = TotalAmt + Convert.ToDouble(Amt);                              
            }
 
            //Display Total
            int RowTot = dgvPTDetails.Rows.Count + 7;
            excel.Cells[RowTot, 2] = "Total : ";
            wRange = (Range)excel.Cells[RowTot, 2];
            wRange.Font.Bold = true;
 
            excel.Cells[RowTot, 4] = TotalAmt.ToString();
            wRange = (Range)excel.Cells[RowTot, 4];
            wRange.Font.Bold = true;
        }

 


Also See those links :

http://www.eggheadcafe.com/community/aspnet/2/42640/autofit-column.aspx
http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_23505519.html
http://www.c-sharpcorner.com/UploadFile/mgold/Query2Excel12032005011029AM/Query2Excel.aspx

see that article also:
http://www.eggheadcafe.com/forumpost.aspx?topicid=2&forumpostid=3954

Use this code...  Use this code...
27-Aug-08 03:19 AM

Code:

Range oRng = null;

oRng = Excel.get_Range("A1","A1");

oRng.AutoFit();
Not Working  Not Working
27-Aug-08 03:22 AM
I just want the property that can select the selection mode of whole sheet and auto fit the columns
Try this  Try this
27-Aug-08 03:31 AM
 

public void SetColumnWidth(Worksheet ws, int col, int width)
{
((Range)ws.Cells[1, col]).EntireColumn.ColumnWidth = width;
}
// autofit to contents
public void AutoFitColumn(Worksheet ws, int col)
{
((Range)ws.Cells[1, col]).EntireColumn.AutoFit();
}

May be this will solve your problem.

Just go thr this link;

http://www.c-sharpcorner.com/UploadFile/mgold/Query2Excel12032005011029AM/Query2Excel.aspx

Best Luck!!!!!!!!!!
Sujit.

Use this  Use this
27-Aug-08 03:37 AM

Use this:

ObjWorkSheet.EntireColumn.AutoFit();

No property like this............  No property like this............
27-Aug-08 04:22 AM

ObjWorkSheet.EntireColumn.AutoFit();

I want property that can do this

AutoFit  AutoFit
27-Aug-08 06:17 AM

Dear you are missing small thing

 

Do it like this

 

oWorksheet.Cells.Select(); // Missing this…………

oWorksheet.Columns.Autofit();

oWorksheet.Rows.Autofit();

THANKS ALOT  THANKS ALOT
27-Aug-08 06:42 AM

It is really great thing to me.......

one again thanks alot

Create New Account
help
Vanishing data when rows are copied between worksheets Office I have a problem that I can't solve. I have an Excel workbook with two worksheets. One worksheet shows all "Outstanding" issues, the other shows all "Resolved" issues. The structure of the worksheets is identical. When an issue is resolved, the status of the issue on the workbook say, I can't recreate the problem. I've taken the last saved version of workbooks where this has happened, and tested it, and everything worked fine. But I'm reluctant that the users are doing, as I can't see how they'd get the workbooks to do this either (without a lot of work on their part). Office Developer VBA Discussions Excel (1) Database (1) Resolved (1) Entire (1) Columns (1) Hidden (1) Worksheets (1) Problem (1) Are you copying the entire row or each cell? Another idea would
me ?? Thank you, Eric My code . . . . function openAndPasteInExcel() { var excel = new ActiveXObject('Excel.Application'); var workBooks = excel.Workbooks.Add; var excelSheet = workBooks.Worksheets(1); excelSheet.Application.Visible = true; excelSheet.Activate(); excel.ActiveSheet.Range('A1').Select; excel.ActiveSheet.PasteSpecial new ActiveXObject ( "Excel.Application" ); / / Silent-mode: xlApp . Visible = true ; xlApp . DisplayAlerts = false ; var xlBook = xlApp . Workbooks . Add (); xlBook . worksheets ( "Sheet1" ). activate ; var XlSheet = xlBook . activeSheet ; XlSheet . Name = "Company Report" ; / / Store the sheet header names Add reference to Microsoft Excel 11.0 Library from COM tab and imports Imports Microsoft.Office.Interop / / Create instance to Excel Excel.Application oxL = new Excel.Application(); / / Suppress any popup to continue automation oxL.DisplayAlerts = false; / / Add work book Excel.Workbooks wBooks = oxL.Workbooks; / / get Work Book Excel.Workbook book = wBooks.Add; / / Get the First Sheet
Multiple Worksheets Windows 7 Version: 2008 Operating System: Mac OS X 10.6 (Snow Leopard) How can I copy same info between worksheets? MAC Office Excel Discussions Worksheets (1) Office (1) Clustered (1) Snow Leopard (1) Otherwise (1) Copy paste (1) You need to be work, but storing duplicate copies of the same data on multiple sheets [or in multiple workbooks] is redundant & inefficient. I am sure you are clear in your own mind what you becomes confusing for those trying to reply or follow the conversation. Regards | :> ) Bob Jones [MVP] Office:Mac On 5 / 29 / 10 8:01 AM, in article 59bb9257.-1@webcrossing.JaKIaxP2ac0, keywords: Multiple, Worksheets description: Version: 2008 Operating System: Mac OS X 10.6 (Snow Leopard) How can I
Link to cells in other worksheets & workbooks Excel I just got a new computer & installed Excel 2002. On my old computer I used to be able to create formulas that linked to cells in other worksheets or workbooks. I would just type = then select the worksheet tab & then click on whatever cell I when I try to do that it won't let me select cells in other worksheets or workbooks (it's like when you try to click on a cell in a protected worksheet the same worksheet as the formula. The links still exist & can be updated in the workbooks that were created on my old machine, but I can't make new ones. None of the workbooks are protected. I'm not sure if it makes any difference but my old computer
Copy data from multiple workbooks / worksheets into Master worksheet, Macro (posted to Excel Forum, probably should have posted here) Folks: My the folder. Also, I don't want to start with the master worksheet inside the workbooks that we are copying from because there are 100 of them and each has a the one example, but do not want to have to do that for all 100 workbooks. Thank you - Rowland Here is the first macro that copies the data from all worksheets except the master) in the active workbook into the master worksheet: (note some of the strData As String Dim RowCount As Integer Application.ScreenUpdating = True ActiveSheet.Unprotect "forms" Set wsMaster = Worksheets("Summary") lngMasterLastRow = Cells(65536, 1).End(xlUp).Row + 1 For Each ws In Worksheets If UCase(wSheet.Name) = "SUMMARY" Then Else With ws ws.Activate ActiveSheet.Unprotect "forms" Range False .FileType = msoFileTypeExcelWorkbooks If .Execute() > 0 Then For i = 1 To .FoundFiles.Count Set wb = Workbooks.Open(.FoundFiles(i)) yourSubHere wb.Close False Next i End If End With Private Sub