using System;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public class excel_n
{
static void Main()
{
string source = "E:\\archivos\\source.xls"; //debe existir
string destiny = "E:\\archivos\\destiny.xls"; //debe existir
string temp = "E:\\archivos\\destiny_temp.xls";
copy(source,destiny,temp);
Console.ReadKey();
}
public static void copy(string source,string destiny,string temp)
{
//source
Excel.Application xlAppSource;
Excel.Workbook xlWorkBookSource;
Excel.Worksheet xlWorkSheetSource;
Excel.Range rangeSource;
//destiny
Excel.Application xlAppDestiny;
Excel.Workbook xlWorkBookDestiny;
Excel.Worksheet xlWorkSheetDestiny;
Excel.Range rangeDestiny;
string str;
int rCnt = 0;
int cCnt = 0;
//Apps
xlAppSource = new Excel.ApplicationClass();
xlAppDestiny = new Excel.ApplicationClass();
//Source
xlWorkBookSource = xlAppSource.Workbooks.Open(source, 0, false, 5, null, null, false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, null, true, false, 0, true, false, false);
xlWorkSheetSource = (Excel.Worksheet)xlWorkBookSource.Worksheets.get_Item(1);
rangeSource = xlWorkSheetSource.UsedRange;
//Destiny
xlWorkBookDestiny = xlAppDestiny.Workbooks.Open(destiny, 0, false, 5, null, null, false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, null, true, false, 0, true, false, false);
xlWorkSheetDestiny = (Excel.Worksheet)xlWorkBookDestiny.Worksheets.get_Item(1);//hoja BASE
rangeDestiny = xlWorkSheetDestiny.UsedRange;
for (rCnt = 1; rCnt <= rangeSource.Rows.Count; rCnt++)
{
for (cCnt = 1; cCnt <= rangeSource.Columns.Count; cCnt++)
{
str = (string)(rangeSource.Cells[rCnt, cCnt] as Excel.Range).Text;
//xlWorkSheetDestiny.Cells[rCnt, cCnt] = 10;
xlWorkSheetDestiny.Cells[rCnt, cCnt] = xlWorkSheetSource.Cells[rCnt, cCnt];
Console.WriteLine(str);
}
}
//xlWorkBook.Save();
//xlWorkBook.Close(true, source);
//Source
xlWorkBookSource.Close(false,null,null);
xlAppSource.Quit();
//Destiny
xlWorkBookDestiny.Close(true, temp, null); //guarda destiny con otro nombre
xlAppDestiny.Quit();
releaseObject(xlWorkSheetSource);
releaseObject(xlWorkBookSource);
releaseObject(xlAppSource);
releaseObject(xlWorkSheetDestiny);
releaseObject(xlWorkBookDestiny);
releaseObject(xlAppDestiny);
}
public static void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
Console.WriteLine("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}
Fuente
Csharp.net