How to copy to specific row in target sheet?
I need to copy A1 to J10 from a sheet in one excel to location starting from A15 in second excel sheet. How can I achieve this in c#? In the below Copy method there seems to be no option to specify the location in target excel sheet.
ObjWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)ObjWorkBookTemp.Sheets[1];
ObjWorkSheet.Copy(Type.Missing, ObjWorkBookGeneral.Sheets[1]);
I think you are using the wrong method here... you want to use a Paste method not a copy method.
Try the Range.PasteSpecial method... should do the trick for you.
Something like this...
Excel.Range sourceRange = firstWorksheet.get_Range("A1", "J10");
Excel.Range destinationRange = secondWorksheet.get_Range("A15", "J25");
sourceRange.Copy(Type.Missing);
destinationRange.PasteSpecial(Microsoft.Office.Interop.Excel.XlPasteType.xlPasteFormulas, Microsoft.Office.Interop.Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);
Related
Is there a way to create an Excel workbook without any sheets in it?
This is the code that I use to create the workbook:
excelApp = new Microsoft.Office.Interop.Excel.Application();
excelBook = excelApp.Workbooks.Add();
I tried also adding
excelApp.SheetsInNewWorkbook = 0;
before the creation of the excelBook but the minimum value is 1 so the program crashes.
EDIT:
Tried also to delete the first sheet as soon as it is created but still doesn't work
Sheets excelSheetsToDelete = excelBook.Sheets[1];
excelSheetsToDelete.Delete();
I would like to be able to add my sheets with my names later without having to rename the first one.
You can't create an Excel without any sheet, Excel must contain at least one sheet. Try to delete single sheet in Excel application (desktop). You won't do that.
Like people have already said, Excel must contain at least 1 visible worksheet at all times. Since it seems like you just want to create a workbook, and manually specify your sheet name without having to rename the one created automatically, I wrote this quick VB Script that may work for you.
Dim objShell, objExcel, objWorksheet, strSheetName
strSheetName = InputBox("Enter a name for your new Worksheet:")
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run("EXCEL.EXE")
WScript.Sleep 3000 'Wait for new excel file to open
Set objExcel = GetObject(, "Excel.Application")
Set objWorksheet = objExcel.ActiveWorkbook.Worksheets(1)
objWorksheet.Name = strSheetName
What this does is prompt you to enter a name for your new sheet. It then runs a new instance of Excel and sets the first worksheet of the newly created file as the name you specified.
If Excel includes 3 sheets when creating new workbooks, you can change this to 1 by going in any excel worbook and clicking - File > Options > General - and look for the "When the creating new workbooks" separator. There will be an option "Include this many sheets" which you can change to 1.
Also, to confirm what people have already said, if you try and change this value to 0, it will tell you "The entry must be greater than or equal to 1" meaning all workbooks must contain at least 1 visible worksheet. Hope this helped.
I have found two ways those were being used by people if we want to read or write to a cell in an excel.
Declaration:
Excel.Application ExcelApp = new Excel.Application();
Excel.Workbook srcWorkBook = ExcelApp.Workbooks.Open(#"C:\test.xls");
Excel.Worksheet srcWorkSheet = srcWorkBook.Worksheets[1];
Excel.Range srcRange = srcWorkSheet.UsedRange;
Usage 1:
srcWorkSheet.Cells[1, 1].value2 = "foo bar";
Usage 2:
srcRange.Cells[2, 2].Value2 = "foo bar";
Which one is the best way to use ? or it's all fine in .NET ?
The two ways are very different.
srcWorkSheet.Cells[1, 1].value2 = "foo bar";
The 1. usage refers to the A1 cell of the first worksheet.
MSDN Worksheets.Cells property Excel
srcRange.Cells[2, 2].Value2 = "foo bar";
The 2. usage takes the cell on the 2. row, 2. column of the UsedRange. If the UsedRange in Excel is B2:D5, it would put value at C3:
MSDN Worksheets.Range Property Excel
Having a variable named Range as the Range class is really not a great idea. The same goes for WorkSheet and WorkBook.
Either option will work, but they get messy as soon as you have to modify the layout of the worksheet.
If it's an option, I like to add named ranges. This works particularly well if you're using a template where you can modify the "starting" state of the workbook.
Let's say you have a series of columns, and one of them contains the "foo" value. You can add a name like "fooColumn" to the entire column or the top cell in the column.
Then you can get the column number using
worksheet.Range("fooColumn").Column
That protects you from having to manually edit column or row numbers all over the place if you move elements around on your worksheet.
And to second what others have said, use EPPlus instead of Interop. You can still use named ranges. But EPPlus is good and Interop can bring all sorts of pain when COM objects aren't released. Interop automates an application that manipulates the file. EPPlus just works with the file.
I have one workbook with three sheets. Each sheet got 3 pages. What I want to reach is: I want to save only the first page of each sheet.
I can only count those pages with
int numberOfPages = 0;
foreach(Excel.Worksheet sheet in excelWorkbook.Sheets)
{
numberOfPages += sheet.PageSetup.Pages.Count;
}
But I cant find a way how to save these pages. Is there a way?
Here is how to copy a worksheet:
Excel.Worksheet worksheet1 = ((Excel.Worksheet)Application.ActiveWorkbook.Worksheets[1]);
Excel.Worksheet worksheet3 = ((Excel.Worksheet)Application.ActiveWorkbook.Worksheets[3]);
worksheet1.Copy(worksheet3);
Hope that helps.
I'd suggest using the Macro Recorder in such cases (which is available in Excel). The required VBA code can generated automatically in the background for you. Most probably you will need to correct it because an auto-generated code is not well-optimized, but at least you will have an idea what properties and methods should be used to get the job done. See Create or delete a macro for more information.
I currently have a routine which reads rows/columns and writes into a SQL table from a SELECT statement.
We were thinking of then reading the SQL table and updating an empty Excel worksheet. What I would like to do is read and then update the data directly into Excel.
My program currently does the following:
Opening the workbook.
Accessing the different worksheets.
Saving As a new workbook name.
Closing Excel.
I just need an example that:
will allow the first row to be the column names
then read out the data into the various cells for each row.
I do not recommend using COM Interop either.
You can find here a sample about exporting dataset to Excel in C#.
It requires an Excel tool named EasyXLS.
to open the file you can do it like that:
Dim exAppl As New Excel.Application
exAppl.Visible = True
Dim exMappe As Excel.Workbook = exAppl.Workbooks.Open("C:\... .xlsx", , False)
You can acces to a Cell with
Console.WriteLine(exAppl.Range("A2").Value())
or when you whant to go throw it use something like that:
For i As Integer = 1 To exAppl.Rows.Count
Dim a As Excel.Range = exAppl.Rows(i)
For j As Integer = 1 To a.Columns.Count
Dim b As Excel.Range = a.Columns(j)
Console.WriteLine(b.Value)
Next
Next
What's the better way to insert cell comments in excel 2007 files programmatically using c# and .net 3.5?
I just did exactly that but with MS Word (using Microsoft.Office.Interop.Word
range.Comments.Add ( range, ref _categoryMessage );
So, I would suggest using Microsoft.Office.Interop.Excel and the similar method.
Consider this from MSDN:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel.range.addcomment
Also see this too
The accepted answer points in the right direction, but the correct syntax is:
Excel.Range cell;
cell.AddComment("My comment");
Excel._Worksheet oSheet =
(Microsoft.Office.Interop.Excel._Worksheet) excelWorkbook.ActiveSheet;
oSheet.Cells[2, 3].Cells.AddComment("Selam");
Have you tried using VSTO ? You can easily load an Excel document and manipulate it. To add a comment to a cell, load the file, activate the worksheet, then select the cell as a range and set the comment.