Copying excel worksheet to a different workbook - c#

I'm trying to copy a worksheet to a different workbook into the last worksheet of the target workbook.
My workbooks and worksheets are created like this:
public Microsoft.Office.Interop.Excel.Workbook xlWorkbookMatrix;
public Microsoft.Office.Interop.Excel._Worksheet xlWorksheetMatrix;
I tried using worksheet.copy:
xlWorksheetMatrix.Copy(Type.Missing, xlWorkbookEvaluation.Sheets[xlWorkbookEvaluation.Sheets.Count]);
and worksheet.UsedRange.Copy:
xlWorksheetMatrix.UsedRange.Copy(xlWorkbookEvaluation.Sheets[xlWorkbookEvaluation.Sheets.Count]);
With both different methods I always get an error.
For worksheet.Copy:
System.Runtime.InteropServices.COMException occured in System.Dynamic.dll
The Copy-property of the worksheet object can't be assigned
For worksheet.UsedRange.Copy:
System.Runtime.InteropServices.COMException occured in System.Dynamic.dll
The Copy-property of the Range object can't be assigned

Having a template sheet you want to fill many times, Hope this helps :
public void test()
{
Excel.Application excelApp;
string fileTarget = "C:\target.xlsx";
string fileTemplate = "C:\template.xlsx";
excelApp = new Excel.Application();
Excel.Workbook wbTemp, wbTarget;
Excel.Worksheet sh;
//Create target workbook
wbTarget = excelApp.Workbooks.Open(fileTemplate);
//Fill target workbook
//Open the template sheet
sh = wbTarget.Worksheets["TEMPLATE"];
//Fill in some data
sh.Cells[1, 1] = "HELLO WORLD!";
//Rename sheet
sh.Name = "1. SHEET";
//Save file
wbTarget.SaveAs(fileTarget);
//Iterate through the rest of the files
for (int i = 1; i < 3; i++)
{
//Open template file in temporary workbook
wbTemp = excelApp.Workbooks.Open(fileTemplate);
//Fill temporary workbook
//Open the template sheet
sh = wbTemp.Worksheets["TEMPLATE"];
//Fill in some data
sh.Cells[1, 1] = "HELLO WORLD! FOR THE " + i + ".TH TIME";
//Rename sheet
sh.Name = i + ". SHEET";
//Copy sheet to target workbook
sh.Copy(wbTarget.Worksheets[1]);
//Close temporary workbook without saving
wbTemp.Close(false);
}
//Close and save target workbook
wbTarget.Close(true);
//Kill excelapp
excelApp.Quit();
}

Related

Will this work if I change the active sheets throughout my code?

I am running a script to format sheets in an existing excel file. Here is what I have now:
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmm");
try
{
string FileName = Dts.Variables["User::DestinationFilePath1"].Value.ToString();
string FolderName = Dts.Variables["User::DestinationFolder1"].Value.ToString();
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.Visible = false;
Workbook xlWorkbook = xlApp.Workbooks.Open(FileName);
Sheets xlSheets = xlWorkbook.Worksheets;
Worksheet sheet = (Worksheet)xlApp.Worksheets[1];
sheet.Select(Type.Missing);
xlWorkbook.Save();
xlWorkbook.Close(true);
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["User::DestinationFilePath1"].Value.ToString() + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
It doesn't do anything at the moment, just opens the workbook and sets the active worksheet. There are 3 different sheets in the workbook that I need to format, so would I be able to do this like so?:
try
{
string FileName = Dts.Variables["User::DestinationFilePath1"].Value.ToString();
string FolderName = Dts.Variables["User::DestinationFolder1"].Value.ToString();
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.Visible = false;
Workbook xlWorkbook = xlApp.Workbooks.Open(FileName);
Sheets xlSheets = xlWorkbook.Worksheets;
Worksheet sheet = (Worksheet)xlApp.Worksheets[1];
sheet.Select(Type.Missing);
//do work here
Worksheet sheet = (Worksheet)xlApp.Worksheets[2];
sheet.Select(Type.Missing);
//do work here
Worksheet sheet = (Worksheet)xlApp.Worksheets[3];
sheet.Select(Type.Missing);
//do work here
xlWorkbook.Save();
xlWorkbook.Close(true);
Dts.TaskResult = (int)ScriptResults.Success;
}

Writing a value to an already open workbook using c#

I have an excel workbook that has a button, that triggers a c# application. I need to add the returned value from the app to the excel workbook but I can't figure out how to do that while the excel workbook is already open.
I've basically been grasping at straws. Every example I've found opens a read only version of the excel workbook
Microsoft.Office.Interop.Excel._Application myExcelApp;
Microsoft.Office.Interop.Excel.Workbook myExcelWorkbook = new
Microsoft.Office.Interop.Excel.Workbook();
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
xlWorkSheet = myExcelWorkbook.Sheets["Sheet1"];
xlWorkSheet = myExcelWorkbook.ActiveSheet;
myExcelApp = new Microsoft.Office.Interop.Excel.Application();
myExcelApp =
(Microsoft.Office.Interop.Excel.Application)
System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
foreach (Microsoft.Office.Interop.Excel.Workbook item in myExcelApp.Workbooks)
{
//Select the excel target 'NAME'
if (item.Name == "DatagridviewTest.xlsm")
{
myExcelWorkbook = item;
break;
}
//Select the target workbook
xlWorkSheet = myExcelWorkbook.Sheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
//Set cell value
xlWorkSheet.Cells[5, 1] = "new value";
}
I get an unhandled exception error "System runtime COM exception"

C# Open new Excel Workbook and Add Data

From a console application using C# I am trying to open a new Excel workbook and add data to it. I can open a new workbook fine, but I am running into issues adding data to the workbook because my range object is null, and I can't seem to hook into the excel workbook that was just opened. I tried a variation of ActiveWorkbook, Sheets[1] and a couple of others and I can't seem to figure it out
using Microsoft.Office.Interop.Excel;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Application xl = null;
_Workbook wb = null;
// Option 1
xl = new Application();
xl.Visible = true;
wb = (_Workbook)(xl.Workbooks.Add(XlWBATemplate.xlWBATWorksheet));
Worksheet sheet = xl.ActiveWorkbook.ActiveSheet;
Range cell = sheet.Cells[1, 1];
//ERROR on cell.Value("Test");
cell.Value("Test");
}
}
}
This code may be help you.
using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "Excel Workbook|*.xls" })
{
if (sfd.ShowDialog() == DialogResult.OK)
{
// creating Excel Application
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
// creating new Excelsheet in workbook
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
// see the excel sheet behind the program
app.Visible = true;
// get the reference of first sheet. By default its name is Sheet1.
// store its reference to worksheet
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
// changing the name of active sheet
worksheet.Name = "Exported from gridview";
// storing header part in Excel
for (int i = 1; i < DGView.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = DGView.Columns[i - 1].HeaderText;
}
// storing Each row and column value to excel sheet
for (int i = 0; i < DGView.Rows.Count - 1; i++)
{
for (int j = 0; j < DGView.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = DGView.Rows[i].Cells[j].Value.ToString();
}
}
// save the application
workbook.SaveAs(sfd.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// Exit from the application
app.Quit();
}
}
I used this code in my work for saving datagridview as excel sheet and it has been worked well.

how to copy and paste an excel sheet with source formatting in c# window application?

i tired this code but it only paste the copied sheet as a embed sheet in my destination location. i want to create to create a window application that should make a copy of source excel file and paste to destination location.kindly help me
Excel.Application srcxlApp;
Excel.Workbook srcworkBook;
Excel.Worksheet srcworkSheet;
Excel.Range srcrange;
Excel.Application destxlApp;
Excel.Workbook destworkBook;
Excel.Worksheet destworkSheet;
Excel.Range destrange;
string srcPath;
string destPath;
//Opening of first worksheet and copying
srcPath = tbpath.Text;
srcxlApp = new Excel.Application();
srcworkBook = srcxlApp.Workbooks.Open(srcPath);
srcworkSheet = srcworkBook.Worksheets.get_Item(1);
srcrange = srcworkSheet.UsedRange;
srcrange.Copy(Type.Missing);
//opening of the second worksheet and pasting
destPath = "C:\\Users\\Dell\\Desktop\\don\\Book1.xlsx";
destxlApp = new Excel.Application();
destworkBook = destxlApp.Workbooks.Open(destPath, 0, false);
destworkSheet = destworkBook.Worksheets.get_Item(1);
destrange = destworkSheet.Cells[1, 1];
// destrange.Select();
destworkSheet.PasteSpecial(Excel.XlPasteType.xlPasteAll, Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);
// destworkSheet.PasteSpecial(Type.Missing, Type.Missing);
destworkBook.SaveAs("C:\\Users\\Dell\\Desktop\\don" + DateTime.Now.ToString("MM_dd_yyyy") + ".xlsx");
srcxlApp.Application.DisplayAlerts = false;
destxlApp.Application.DisplayAlerts = false;
destworkBook.Close(true, null, null);
destxlApp.Quit();
srcworkBook.Close(false, null, null);
srcxlApp.Quit();

Open, Modify, SaveAs an Excel Workbook in the background (Winforms, C#)

in my app, I've saved a copy of a blank excel file form as a resources, I need to load this file, modify its both worksheets, save it in a new location with a new name.
user should not see that process.
I'm using C# 2010 with a SQL server, from which I'm gonna load my data and put it in the excel form.
Thank You For Your Time.
Use the Microsoft Interop Assemblies that can be found in .NET or COM (Microsoft.Office.Interop.Excel)
Then load all the required cells into a List and modify the data.
Something like this (code below):
string path = #"C:\temp\test.xls";
ApplicationClass excelApllication = null;
Workbook excelWorkBook = null;
Worksheet excelWorkSheet = null;
excelApllication = new ApplicationClass();
System.Threading.Thread.Sleep(2000);
excelWorkBook = excelApllication.Workbooks.Add();
excelWorkSheet = (Worksheet)excelWorkBook.Worksheets.get_Item(1);
// Attention: 1 indexed cells, [Row, Col]
excelWorkSheet.Cells[1, 1] = "Column A, Row 1";
excelWorkSheet.Cells[2, 5] = "Column E, Row 2";
excelWorkSheet.Cells[3, 3] = "Column C, Row 3";
excelWorkBook.SaveAs(path, XlFileFormat.xlWorkbookNormal);
excelWorkBook.Close();
excelApllication.Quit();
Marshal.FinalReleaseComObject(excelWorkSheet);
Marshal.FinalReleaseComObject(excelWorkBook);
Marshal.FinalReleaseComObject(excelApllication);
excelApllication = null;
excelWorkSheet = null;
//opens the created and saved Excel file
Process.Start(path);
That should happen inside a Thread, because you don't want a user to notice that task.
http://msdn.microsoft.com/en-us/library/aa645740%28v=vs.71%29.aspx
(Threading Tutorial)
I would try to avoid automating Excel if at all possible and use the OpenXML SDK (or a library wrapping the OpenXML SDK) for this task.
Here is an article that could help you get started.
I think you wanted to do this... at least worked for me. :)
private void btnExcel_Click(object sender, EventArgs e)
{
string newDirectoryPath = ValidateDirectory();
string newFilePath = Path.Combine(newDirectoryPath, "new.xls");
//brand new temporary file
string tempPath = System.IO.Path.GetTempFileName();
//to manage de temp file life
FileInfo tempFile = new FileInfo(tempPath);
//copy the structure and data of the template .xls
System.IO.File.WriteAllBytes(tempPath,Properties.Resources.SomeResource);
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(tempPath, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//WorkTheExcelFile();
tempFile.Delete();
xlWorkBook.SaveAs(newFilePath);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
Process.Start(newFilePath + ".xlsx");
}

Categories

Resources