I basically need my code to read one by one all cells in an excel file and then upload then to a database.
I've read on several answers to this question I should use the UsedRange but everytime I do I get an error saying there is no definition for UsedRange.
I added a reference to the excel interop but no dice.
Any advice would be appreciated.
And I know the code looks terrible now but I just wanted to test if I could read data from an excel file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication28
{
class Program
{
static void Main()
{
Excel.Application excelApp = new Excel.Application();
excelApp.Visible = true;
string workbookPath = "C:/Users/Sidney/Desktop/CrystalViewer-11.xls";
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath,
0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
Excel.Sheets excelSheets = excelWorkbook.Worksheets;
string currentSheet = "Sheet1";
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);
Excel.Range range;
range = excelSheets.UsedRange;
int rows_count = range.Rows.Count;
string output = null;
}
}
}
You're trying to access UsedRange on the wrong Object. UsedRange is a property of Worksheet, so your code should be:
range = excelWorksheet.UsedRange;
Excel.Range xlRange = excelWorkbook.ActiveSheet.UsedRange;
Related
I'm writing a program that copy specific columns from pre-generated .csv file to template xlsx file. With my code I'am only able to achive copying the whole csv file to the first column. Any tips how to make the program see " ; " as a separator during pasting?
Also if I overpass this problem how to copy only specific columns that i choose?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
namespace Kreator
{
class Program
{
static void Main(string[] args)
{
Excel.Application srcApp;
Excel.Workbook srcWorkbook;
Excel.Worksheet srcWorksheet;
Excel.Application destApp;
Excel.Workbook destWorkbook;
Excel.Worksheet destWorksheet;
string srcPath = "C:\\Users\\Desktop\\Raport.csv";
string destPath = "C:\\Users\\Desktop\\XXX.xlsx";
srcApp = new Excel.Application();
srcWorkbook = srcApp.Workbooks.Open(srcPath);
srcWorksheet = srcWorkbook.Worksheets.get_Item(1);
destApp = new Excel.Application();
destWorkbook = destApp.Workbooks.Open(destPath,0,false);
destWorksheet = destWorkbook.Worksheets.get_Item(1);
Excel.Range srcRange = srcWorksheet.get_Range("A1", "C20");
Excel.Range destRange = destWorksheet.get_Range("C10","E29");
srcRange.Copy(Type.Missing);
destRange.PasteSpecial(Microsoft.Office.Interop.Excel.XlPasteType.xlPasteValu es, Microsoft.Office.Interop.Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone);
destWorkbook.SaveAs("C:\\Users\\Desktop\\GotowyPlik" + DateTime.Now.ToString("MM_dd_yyyy") + ".xlsx");
srcApp.Application.DisplayAlerts = false;
destApp.Application.DisplayAlerts = false;
srcWorkbook.Close(false, null, null);
destWorkbook.Close(true, null, null);
destApp.Quit();
srcApp.Quit();
}
}
}
I have an excel file in which some cell values are generating dynamically using macro.
File is also read-only.
I have to read these dynamically generated values using c# code.
Use following macro code to generate cell values:
**Sub abc()
Range("E5").Value = "string"
Range("E6").Value = 2
End Sub**
Thank You...!
Check if you need to connect to already opened excel file.
If you use excelApp.Workbooks.Open, it is not reflecting sheet data updated by macros.
Instead, try BindToMoniker method as follows:
private void btnGetXLSValue_Click(object sender, EventArgs e)
{
object _row = 5;
object _column = 5;
Excel.Application excelApp = new Excel.Application();
excelApp.Visible = false;
excelApp.ScreenUpdating = false;
excelApp.DisplayAlerts = false;
Microsoft.Office.Interop.Excel.Workbook excelWorkbook ;//= excelApp.Workbooks.Open(#"C:\July.xlsm", 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Get a reference to the Workbook object by using a file moniker.
//The xls was saved earlier with this file name.
excelWorkbook = (Excel.Workbook)System.Runtime.InteropServices.Marshal.BindToMoniker(#"C:\July.xlsm");
Microsoft.Office.Interop.Excel.Sheets excelSheets = excelWorkbook.Worksheets;
string currentSheet = "July 2015";
Microsoft.Office.Interop.Excel.Worksheet excelWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheets.get_Item(currentSheet);
Microsoft.Office.Interop.Excel.Range range = (Microsoft.Office.Interop.Excel.Range)excelWorksheet.UsedRange;
string sValue = (range.Cells[_row, _column] as Microsoft.Office.Interop.Excel.Range).Value2.ToString();
//string sValue = (range.Cells[_row, _column] as Microsoft.Office.Interop.Excel.Range).get_Value(range).ToString();
MessageBox.Show(sValue);
}
I am writing a C# program which copies a range of cells from a worksheet of one workbook to a worksheet of an other workbook. But the problem I am facing is I am only able to copy and paste the whole worksheet of first workbook. I want to know how to select only a specific range(from row 5 [column 1 to column 10] to row 100 [column 1 to column 10]) and paste it in second workbook worksheet starting from row 2 column 8.
Also i want to know how a fill a column say from C1 to C100 with some value in a direct way instead of using the loop like below
for(i=1;i<2;i++)
{
for(j=1;j<101;i++)
{
worksheet.cells[i,j]="Fixed";
}
}
Here is the code that i have written so far
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
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="C:\\Documents and Settings\\HARRY\\Desktop\\incident.csv";
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:\\Documents and Settings\\HARRY\\Desktop\\FIXED Aging incident Report.xls";
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.Paste(Type.Missing, Type.Missing);
destworkBook.SaveAs("C:\\Documents and Settings\\HARRY\\Desktop\\FIXED Aging incident Report " + DateTime.Now.ToString("MM_dd_yyyy") + ".xls");
srcxlApp.Application.DisplayAlerts = false;
destxlApp.Application.DisplayAlerts = false;
destworkBook.Close(true, null, null);
destxlApp.Quit();
srcworkBook.Close(false, null, null);
srcxlApp.Quit();
}
}
}
You should be able to do this:
Excel.Range from = srcworkSheet.Range("C1:C100");
Excel.Range to = destworkSheet.Range("C1:C100");
from.Copy(to);
mrtig has a very elegant solution. But it won't work if you have the workbooks in separate instances of excel. So, the key is to open them in just one instance. I've modified your example to show using this approach:
public void CopyRanges()
{
// only one instance of excel
Excel.Application excelApplication = new Excel.Application();
srcPath="C:\\Documents and Settings\\HARRY\\Desktop\\incident.csv";
Excel.Workbook srcworkBook = excelApplication.Workbooks.Open(srcPath);
Excel.Worksheet srcworkSheet = srcworkBook.Worksheets.get_Item(1);
destPath = "C:\\Documents and Settings\\HARRY\\Desktop\\FIXED Aging incident Report.xls";
Excel.Workbook destworkBook = excelApplication.Workbooks.Open(destPath,0,false);
Excel.Worksheet destworkSheet = destworkBook.Worksheets.get_Item(1);
Excel.Range from = srcworkSheet.Range("C1:C100");
Excel.Range to = destworkSheet.Range("C1:C100");
// if you use 2 instances of excel, this will not work
from.Copy(to);
destworkBook.SaveAs("C:\\Documents and Settings\\HARRY\\Desktop\\FIXED Aging incident Report " + DateTime.Now.ToString("MM_dd_yyyy") + ".xls");
srcxlApp.Application.DisplayAlerts = false;
destxlApp.Application.DisplayAlerts = false;
destworkBook.Close(true, null, null);
srcworkBook.Close(false, null, null);
excelApplication.Quit();
}
For the First part of setting the same value for the entire range, instead of looping following will work out
range1 = workSheet.get_Range("A1:B100");
range1.Value = "Fixed";
And for copying you can try what #mrtig has suggested.
Hey all, I'm experiencing transposed behavior when working the Excel.Worksheet.Cells array.
My first cell needs to be at [row = 10, column = 3]
My second cell needs to be at [row = 11, column = 17]
Then using these two cells as boundaries, I create a range and merge it.
As you can tell from the values noted above, the range should be mostly horizontal.
So, to help me out, I created a simple helper function that merges cells:
public static void MergeRange(Excel.Worksheet worksheet, int startRowIdx,
int startColIdx, int endRowIdx, int endColIdx, bool across = false)
{ //Get range boundaries.
Excel.Range cells = worksheet.Cells;
//commented out, resolved code is directly below - N. Miller, 9-24-2013
//Excel.Range topleftCell = cells[startColIdx][startRowIdx];
//Excel.Range bottomrightCell = cells[endColIdx][endRowIdx];
Excel.Range topleftCell = cells[startRowIdx, startColIdx];
Excel.Range bottomrightCell = cells[endRowIdx, endColIdx];
//Merge range.
Debug.WriteLine(String.Format("({0}, {1}) to ({2}, {3}).", startRowIdx, startColIdx, endRowIdx, endColIdx));
Excel.Range range = worksheet.get_Range(topleftCell, bottomrightCell);
Excel.Interior interior = range.Interior;
interior.ColorIndex = XLColor.PERIWINKLE; //JUST HIGHLIGHTS RANGE FOR NOW.
//range.Merge(across);
//Cleanup
Marshal.ReleaseComObject(interior);
Marshal.ReleaseComObject(range);
Marshal.ReleaseComObject(bottomrightCell);
Marshal.ReleaseComObject(topleftCell);
Marshal.ReleaseComObject(cells);
}
In the code above, I select the cells I want by swapping the columns and rows. This, contrary to what I expected, results in the desired behavior, but it contradicts the MSDN documentation:
MSDN Worksheet.Cells
In the MSDN documentation they give an example where the row is listed first, then the column follows after.
So my question is this... which is correct?
Should the row be first, or should the column be first?
When I modify my code to be consisten with the MSDN documentation, the highlighted cells are transposed.
If I understand you correctly then when you use say cells[1][2] then it means A2 In such a case, Column comes first and then the row. If you write it as cells[1,2] then you will get B2. In this case, Row comes first and then the Column.
It's the same in Excel-VBA. ?Cells(1)(2).address in immediate window gives $A$2 and ?Cells(1,2).address gives $B$1 If you feel that I have not understood your query then please re-phrase it for me...
Here is the complete code to test it.
NOTE: Tested using VS 2010 Ultimate + Excel 2010
using System;
using System.Windows.Forms;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
Namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
Public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlexcel;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = Missing.Value;
xlexcel = new Excel.Application();
xlexcel.Visible = true;
//~~> Open a File (Change filename as applicable)
xlWorkBook = xlexcel.Workbooks.Open("C:\\SomeFile.xlsx",
0, true, 5, "", "", true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows,
"\t", false, false, 0, true, 1, 0);
//~~> Set Sheet 1 as the sheet you want to work with
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range cells = xlWorkSheet.Cells;
Excel.Range topleftCell = cells[1][2];
MessageBox.Show(topleftCell.Address);
topleftCell = cells[1,2];
MessageBox.Show(topleftCell.Address);
//~~> Once done close and quit Excel
xlWorkBook.Close(false, misValue, misValue);
xlexcel.Quit();
//~~> CleanUp
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlexcel);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}
ScreenShot
Hi i have written code using the Microsoft.Office.Interop.Excel dll but it is not supported online when i published my website. I then found the EPPlus dll witch is supported online but i am having troubles converting the code to use this new dll.
Old Code useing Interop.Excel:
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet[] xlWorkSheet = new Excel.Worksheet[8];
public void ToSpreadSheet()
{
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open(tempFolderPathAlt + "dvforms\\InvestecTemplate.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet[0] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet[1] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);
xlWorkSheet[2] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(3);
xlWorkSheet[3] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(4);
xlWorkSheet[4] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(5);
xlWorkSheet[5] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(6);
xlWorkSheet[6] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(7);
xlWorkSheet[7] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(8);
}
This worked great but now i need to use the EPPlus dll and i'm having problems.
using Excel = OfficeOpenXml;
Excel.ExcelPackage xlApp;
Excel.ExcelWorkbook xlWorkBook;
Excel.ExcelWorksheet[] xlWorkSeet = new Excel.ExcelWorksheet[8];
Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(tempFolderPathAlt + "dvforms\\InvestecTemplate.xlsx");
Excel.ExcelPackage xlApp = new Excel.ExcelPackage(stream);
//This is where the problems begin, xlWorkBook.Worksheets.Add(1) is all underlined in red.
xlWorkSeet[0] = (Excel.ExcelWorksheet)xlWorkBook.Worksheets.Add(1);
How do i load the work sheets from my Excel template? I am unsure if i have done the above correctly, Please help i need it badly.
Thanks in advance.
FileInfo existingFile = new FileInfo(filePath);
using (var package = new ExcelPackage(existingFile))
{
ExcelWorkbook workBook = package.Workbook;
if (workBook != null)
{
if (workBook.Worksheets.Count > 0)
{
int i = 0;
foreach(ExcelWorksheet worksheet in workBook.Worksheets)
{
xlWorkSeet1[i] = worksheet;
i = i + 1;
}
}
}
The function Add() takes in a string parameter that's the name of your worksheet. Try:
xlWorkSeet[0] = (Excel.ExcelWorksheet)xlWorkBook.Worksheets.Add("Sheet1");