Adding a row into a sheet using NetOffice - c#

I have a
Excel.Workbook book = application.Workbooks.Open(txtPathExcel.Text);
Excel.Worksheet mainSheet = (Excel.Worksheet)book.Sheets[1];
How can i add a new row in mainSheet? I can't find any NetOffice functions for it.

All rows are already exist in the sheet, you just need to select the required.
The Rows property of the Application class returns a Range object that represents all the rows on the active worksheet. For example:
Worksheets("Sheet1").Rows(3)
The range object refers to the third row on the sheet.
Also you may find the Insert method helpful. It inserts a cell or a range of cells into the worksheet or macro sheet and shifts other cells away to make space.

Related

Reading from Excel dynamically in C#

I'm not sure if using the word "dynamic" is correct. Anyway, I do have some basic understanding of using the Microsoft.Office.Interop.Excel. The problem is, I'm having about 100 excel files in a folder, each of the excel files has different sheet name, number of rows and number of columns.
As far as I understand, you need to specify the range and sheet name, i.e.:
xcel.Worksheet sheet = someExcelFiles.Sheets["SomeSheetName"] as Excel.Worksheet;
Excel.Range range = sheet.get_Range("A1:A5");
Is there anyway so that my application can read all data in all of the excel files without having to specify the sheet name and range (row and columns)?
Short answer yes. Long answer From DotNetPerls which also contains grabbing number of sheets programatically.
Range excelRange = sheet.UsedRange;
object[,] valueArray = (object[,])excelRange.get_Value(
XlRangeValueDataType.xlRangeValueDefault);

How can i avoid COMException while adding multiple worksheets into a workbook using c# excel introp ?

I am trying to create a workbook having multiple worksheets but i am getting COMException as soon i try to add 6th worksheet in the workbook.
So is there any way to extend worksheets in a workbook ??
If you are using a loop to get your worksheet in a loop and not sure how many sheets are there in the workbook then I would recommend finding the total Sheets count in that workbook and then looping to get the worksheet object
For example
int SheetCount = xlWorkBook.Sheets.Count;
will give you the number of sheets in that workbook which you can use in a For Loop.
If you need more worksheets then you can use xlexcel.Worksheets.Add to get more worksheets.
Followup From Comments:
I tried this approach, and Yes it's not throwing exception when i am trying to get worksheets beyond 5 from workbook. But It's overwriting data (which i am writing for 6th sheet) into 5th sheet only even i try to get 6th worksheet after adding one in workbook. It seems below code snippet returns last available sheet in a workbook which is 5th one. m_ExcelSheet = (Excel._Worksheet)(m_ExcelSheets.get_Item(6)); How to stop overwriting data in the 5th worksheet after adding new worksheets ? – saurabh.mridul 1 min ago
The syntax of adding a worksheet is
expression.Add(Before, After, Count, Type)
If you do not specify the paramenters in the .Add then the worksheet will be added as the first worksheet.
When you loop though the worksheets after adding a worksheet without specifying the parameters then your worksheets(1) becomes the latest worksheet that you added. And hence your worksheet 5 (now worksheet 6) gets overwritten.
You need to specify that the new worksheet that you are adding has to be added at the end of the existing worksheets.
Description of parameters
Before: (Optional) (Data Type: Variant) An object that specifies the sheet before which the new sheet is added.
After: (Optional) (Data Type: Variant) An object that specifies the sheet after which the new sheet is added.
Count: (Optional) (Data Type: Variant) The number of sheets to be added. The default value is one.
Type: (Optional) (Data Type: Variant) Specifies the sheet type. Can be one of the following XlSheetType constants: xlWorksheet, xlChart, xlExcel4MacroSheet, or xlExcel4IntlMacroSheet. If you are inserting a sheet based on an existing template, specify the path to the template. The default value is xlWorksheet.
Here is an example on how to add a worksheet at the end.
//~~> Add a new worksheet at the end of the worksheets
xlWorkSheet = xlWorkBook.Sheets.Add(Type.Missing, xlWorkBook.Sheets[xlWorkBook.Sheets.Count], Type.Missing, Type.Missing);

Copy excel rows programatically with column widths

hope someone can help. i have an excel workbook and in that i have several sheets.
what i want to do is get row 1 from sheet named "Sheet1" and paste it into several other sheets (not all). Also, i want to maintain the column widths of row 1 from sheet 1 while copying, this is actually very important.
i mention several other sheets because i would like exclude some sheets, which i am planning to store in a list.
Microsoft.Office.Interop.Excel.Application xlApp = null;
Excel.Workbook xlWorkbook = null;
Excel.Sheets xlSheets = null;
Excel.Worksheet xlNewSheet = null;
any ideas how this can be done in c#?
thanks in advance.
Maintaining the width of a column or a row is very difficult to do. In my opinion: first copy the data, then read the width values of the old columns and apply them to the new columns.
All other solutions which I have seen rely on pastespecial and sometimes do not work.

How to programmatically group (shift select) sheets in Excel

This topic is related to: What object type are multiple selected sheets in Excel?
To give an overview of the problem, I run some code that changes my selection in Excel, and I want to return the selection to what it originally was (I call this "originalSelection"). In most instances, you can just invoke the Select() method on the originalSelection.
var originalSelection = ExcelApp.Selection;
originalSelection.GetType().InvokeMember("Select", System.Reflection.BindingFlags.InvokeMethod, null, originalSelection , null);
With multiple sheets selected, the selection type is always of a range (it's what Excel defaults to). However, if you have multiple sheets selected, you can run into errors when trying to invoke Select again. You need to do some dancing around to get things to work.
If multiple sheets are selected, but not all the sheets, you can do the follow:
selectedSheets.Select();
activeSheet.Activate();
originalSelection.Select(); //this was casted to an Excel.Range
However, if all the sheets are selected, the activeSheet.Activate() line deselects all the other selected sheets. This also happens if you try it natively using the UI.
I was wondering if there is a way to pragmatically mimic shift-selecting sheets one by one through the code? Closest stuff I've found is stuff with range groupings, but nothing for sheets.
I tried to keep my overview brief, but if you need more clarification on what I'm doing, just ask.
So I figured out a way programatically select sheets.
You can create a string array of names, and use the ordering of the array to get a collection of the sheets. Select this collection, and you should have all the specified sheets selected.
String[] sheetsToBeSelected = {"Sheet3","Sheet1","Sheet2"}; //Note, Sheet3 is the first item in this array
excel.Workbook workbook = ExcelApp.ActiveWorkbook; //get your Excel application however you want
excel.Sheets worksheets = workbook.Worksheets; //get all the sheets in this workbook
//This gets a collection of the sheets specified and ordered by the array of names passed in.
//Just call select on this collection, and the first sheet in the collection becomes the active sheet!
((excel.Sheets)worksheets.get_Item(sheetsToBeSelected)).Select();

Adding a new column at the start of an excel table in an excel

I am wondering how one can insert a new column at the beginning of an excel spreadsheet using C sharp.net. I am using Microsoft.Office.Interop.Excel; I want to use OLEO to do this, but I don't see that happening. I have been searching google on how to do this for the last two days now. I can't understand why there are not more tutorials on this?
Checkout out the Range.Insert method which you can call on a range of cells to insert entire rows/columns in front of them:
Worksheet sheet = (Worksheet) workBookIn.Sheets[1]; // Worksheet indexes are one based
Range rng = sheet.get_Range("A1", Missing.Value);
rng.EntireColumn.Insert(XlInsertShiftDirection.xlShiftToRight,
XlInsertFormatOrigin.xlFormatFromRightOrBelow);

Categories

Resources