Excel change cell value of active worksheet - c#

For an excel 2010 plugin, I need a method to change cell values of the active worksheet.
This code works, but opens a new excel window.
How can I change this, to edit the values from the active worksheet?
Microsoft.Office.Interop.Excel.Application objApp;
Microsoft.Office.Interop.Excel.Workbook objBook;
Microsoft.Office.Interop.Excel.Sheets objSheets;
Microsoft.Office.Interop.Excel._Worksheet workSheet;
objApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
objApp.Visible = true;
objBook = (Microsoft.Office.Interop.Excel.Workbook)objApp.ActiveWorkbook;
if (objBook == null)
{
objBook = objApp.Workbooks.Add();
}
// get the collection of sheets in the workbook
objSheets = objBook.Worksheets;
// get the first and only worksheet from the collection of worksheets
workSheet = (Microsoft.Office.Interop.Excel.Worksheet)objSheets.get_Item(1);
workSheet.Cells[1, "A"] = "wert1";

Now I found the solution:
Microsoft.Office.Interop.Excel.Workbook objBook;
Microsoft.Office.Interop.Excel.Sheets objSheets;
Microsoft.Office.Interop.Excel._Worksheet workSheet;
objBook = (Workbook)Globals.ThisAddIn.Application.ActiveWorkbook;
if (objBook == null)
{
objBook = objApp.Workbooks.Add();
}
// get the first and only worksheet from the collection of worksheets
workSheet = (Microsoft.Office.Interop.Excel.Worksheet)objBook.ActiveSheet;
workSheet.Cells[1, "A"] = "value1A";
Source:
http://www.dreamincode.net/forums/topic/199576-getting-current-excel-application-or-workbook-in-c%23/

Related

Export Datatable into Excel Strat from Specific Column C#

I have a datatable and I want export the data into excel but start exporting from a specific column. Scenario, I have an excel sheet and first 5 columns [A-E] have data and want to export from datatable and should start from column F.
How to achieve this in C# console application?
So, the most obvious approach here would be to iterate over the data table's rows and write each to the Excel sheet manually:
Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
// Start Excel and get Application object.
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
// Get a new workbook.
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
// Write the data. Remember that Excel is 1-indexed
int rowIndex = 1;
foreach (DataRow row in table.Rows) {
int colIndex = 6;
foreach (DataColumn col in table.Columns) {
oSheet.Cells[rowIndex, colIndex] = row[col];
colIndex++;
}
rowIndex++;
}
// Save the Excel file
oXL.Visible = false;
oXL.UserControl = false;
oWB.SaveAs("c:\\test\\test505.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// Exit Excel
oWB.Close();
oXL.Quit();
There's probably a more elegant solution to this problem but I think this will get the job done, at least. As a reference, my Excel code was modified from this question, so you might be able to find a better match for your specific needs there.
Alternatively, you could try using the ClosedXML library:
XLWorkbook workbook = new XLWorkbook();
DataTable table = GetYourTable();
var sheet = workbook.Worksheets.Add(table);
var firstColumn = sheet.Column(1);
firstColumn.InsertColumnsBefore(5);
This code works by creating a new Excel worksheet from the datatable, getting a pointer to the first column in the worksheet and then inserting five columns (A - E) before it.
you can use ClosedXML library. example from my code
var wb = new XLWorkbook();
var ws = wb.Worksheets.Add("My Sheet 1");
ws.Cell("A8").Value = "Print by Admin:";
ws.Cell("B8").Value = $"{GetUserById(userId).name} - {GetUserById(userId).position_name}";
ws.Range("B8:C8").Merge();
var range = ws.Cell("B12").InsertTable(data);
range.Style.Border.TopBorder = XLBorderStyleValues.Thin;
range.Style.Border.LeftBorder = XLBorderStyleValues.Thin;
range.Style.Border.RightBorder = XLBorderStyleValues.Thin;
range.Style.Border.BottomBorder = XLBorderStyleValues.Thin;
ws.Row(12).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws.Row(12).Style.Font.Bold = true;
MemoryStream stream = (MemoryStream)GetStream(wb);
return File(stream.ToArray(), ""application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"", "yourfilename.xlsx");
here code for Getstream:
public Stream GetStream(XLWorkbook excelWorkbook)
{
Stream fs = new MemoryStream();
excelWorkbook.SaveAs(fs);
fs.Position = 0;
return fs;
}

I'm importing excel using c # but I want to import the second page

The library I use is microsoft.excel
I cannot use the first page of excel, I only work with the second page.How can I set the number of pages.
this is my code.
excelFile.SaveAs(path);
Excel.Application application = new Excel.Application();
Excel.Workbook workbook = application.Workbooks.Open(path);
Excel.Worksheet worksheet = workbook.ActiveSheet;
Excel.Range range = worksheet.UsedRange;
for (int i = 3; i <= range.Rows.Count; i++)
{
Google lm = new Google();
lm.Default_channel_grouping = ((Excel.Range)range.Cells[i, 1]).Text;
lm.MonthOfYear = ((Excel.Range)range.Cells[i, 2]).Text;
lm.Date = ((Excel.Range)range.Cells[i, 3]).Text;
lm.Segment = ((Excel.Range)range.Cells[i, 4]).Text;
lm.Users = ((Excel.Range)range.Cells[i, 5]).Text;
lm.NewUsers = ((Excel.Range)range.Cells[i, 6]).Text;
lm.Ecommerce = ((Excel.Range)range.Cells[i, 7]).Text;
lm.Transactions = ((Excel.Range)range.Cells[i, 7]).Text;
lm.Revenue = ((Excel.Range)range.Cells[i, 7]).Text;
sdb.Google.Add(lm);
sdb.SaveChanges();
}
You can get the number of sheets (I assume that's what you mean by pages) by accessing the Sheets property of the workbook:
Excel.Application application = new Excel.Application();
Excel.Workbook workbook = application.Workbooks.Open(path);
var sheets = workbook.Sheets.Count;
To work with any sheet in the collection (in your case i = 2)
workbook.Sheets[i]
To add a sheet and make it active, use Sheets.Add
To select a worksheet as active:
((Excel.Worksheet)workbook.Sheets[1]).Select();

How to read Comboboxes Value from Excel using C#

In my application I have a requirement to create an excel file contains several combos.I have created upto that.
Now I have to read those combo's value from excel.
I have found a link to read from excel Read From Excel
But In my code I have found this..
Here is my code
Microsoft.Office.Interop.Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
//Get a new workbook.
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Open("C:\\TopicUpload_2017October14.xls"));
//3rd Sheet
oSheet = (Microsoft.Office.Interop.Excel._Worksheet) oWB.Sheets.get_Item(1);
Microsoft.Office.Interop.Excel.DropDowns allDropDowns = oSheet.DropDowns(Type.Missing);
Microsoft.Office.Interop.Excel.DropDown oneDropdown = allDropDowns.Item("2");
Now how can I get selected text of this dropdown.. When I inspect I got
oneDropdown.ListCount = 5.0; // items count of second drop down, which is true
But could not able to get selected text.
oneDropdown.Text
After searching , I'm able to get it.
#region Read value from excel combobox
Microsoft.Office.Interop.Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
//Get a new workbook.
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Open("C:\\TopicUpload_2017October14.xls"));
//3rd Sheet
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.Sheets.get_Item(1);
Microsoft.Office.Interop.Excel.DropDowns allDropDowns = oSheet.DropDowns(Type.Missing);
Microsoft.Office.Interop.Excel.DropDown oneDropdown = allDropDowns.Item("1"); // first combo
string selectedText = oneDropdown.get_List(oneDropdown.ListIndex);
#endregion

copying of specific range of excel cells from one worksheet to another worksheet

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.

C# - Excel: Delete Row, depending on value in first Column

Imagine, that u have the Column A.
There are 100 Rows and in the Cells are Numbers, like 1, 2, 3 until 100..
How can I programmaticaly (C#) Delete a specific Row, by Example: Deleting the Row which
Value in Column A is 5..
I'm working with the Microsoft.Office.Interop.Excel and thats the related code:
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(#"C:\Users\fre\Desktop\TestDatei.xls");
Microsoft.Office.Interop.Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Microsoft.Office.Interop.Excel.Range xlRange = xlWorksheet.UsedRange;
xlWorksheet.Select(Type.Missing);
Microsoft.Office.Interop.Excel.Range range = xlWorksheet.get_Range("B1:B5", Type.Missing);
range.Delete(Microsoft.Office.Interop.Excel.XlDeleteShiftDirection.xlShiftUp);
because i was interested, too, i did some investigation on the web and created some sample code. maybee this can help you:
private void DeleteCells(object sender, EventArgs e)
{
// create excel-instance:
Excel.Application excel = new Excel.Application();
// open the concrete file:
Excel.Workbook excelWorkbook = excel.Workbooks.Open(#"D:\test.xls");
// select worksheet. NOT zero-based!!:
Excel._Worksheet excelWorkbookWorksheet = excelWorkbook.Sheets[1];
// create a range:
Excel.Range usedRange = excelWorkbookWorksheet.UsedRange;
// iterate range
foreach (Excel.Range r in usedRange)
{
// check condition:
if (r.Value2 == 5.0F)
// if match, delete and shift remaining cells up:
r.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);
}
// save changes (!!):
excelWorkbook.Save();
// cleanup:
if (excel != null)
{
Process[] pProcess;
pProcess = System.Diagnostics.Process.GetProcessesByName("Excel");
pProcess[0].Kill();
}
}
greetings!
jens
If you want to delete the entire row, try this it works
Range usedRanage=sheet.UsedRange;
foreach (Range r in usedRanage)
{
if (Convert.ToString(r.Value2)=="RETRIEVE")
{
r.EntireRow.Delete(XlDeleteShiftDirection.xlShiftUp);
}
}

Categories