I am trying to add a button on an excel worksheet.
According to the example from internet, I am trying to do following code.
using Excel = Microsoft.Office.Interop.Excel;
using VBIDE = Microsoft.Vbe.Interop;
private static void excelAddButtonWithVBA()
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlBook = xlApp.Workbooks.Open(#"PATH_TO_EXCEL_FILE");
Excel.Worksheet wrkSheet = xlBook.Worksheets[1];
Excel.Range range;
try
{
//set range for insert cell
range = wrkSheet.get_Range("A1:A1");
//insert the dropdown into the cell
Excel.Buttons xlButtons = wrkSheet.Buttons();
Excel.Button xlButton = xlButtons.Add((double)range.Left, (double)range.Top, (double)range.Width, (double)range.Height);
//set the name of the new button
xlButton.Name = "btnDoSomething";
xlButton.Text = "Click me!";
xlButton.OnAction = "btnDoSomething_Click";
buttonMacro(xlButton.Name, xlApp, xlBook, wrkSheet);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
xlApp.Visible = true;
}
But it keeps saying "Excel does not contain Button"
What reference should I include to use Button property?
As far as I can tell, Excel.Buttons and Excel.Button do not exist. Instead it is suggested that the correct reference is Microsoft.Office.Tools.Excel.Controls.Button (not Microsoft.Office.Interop.Excel as you are using). This example is from the source below
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlBook = xlApp.Workbooks.Open(#"PATH_TO_EXCEL_FILE");
Excel.Worksheet worksheet = xlBook.Worksheets[1];
Excel.Range selection = Globals.ThisAddIn.Application.Selection as Excel.Range;
if (selection != null)
{
Microsoft.Office.Tools.Excel.Controls.Button button =
new Microsoft.Office.Tools.Excel.Controls.Button();
worksheet.Controls.AddControl(button, selection, "Button");
}
Source: Adding Controls to a Worksheet at Run Time in an Application-Level Project http://msdn.microsoft.com/en-us/library/cc442817.aspx
Using Lesley.Oakey's method requires you to be using the VSTO extension methods in Microsoft.Tools.Office.Excel.
If you are not using them, then you will not be able to access the Worksheet.Controls property.
Best to just use the Worksheet.Shapes container and add a new shape. There's a great post about this here:
Add excel vba code to button using c#
Related
How do I change the view style of Excel Worksheet In Excel interop to a Normal style?
Like this:
Just have no idea :(
Does someone know?
i see just one solution, you have to use ActiveWindow.View: a sample to use it
using Excel = Microsoft.Office.Interop.Excel;
object missing = System.Reflection.Missing.Value;
Excel.Application excel = new Excel.Application();
Excel.Workbooks wbs = excel.Workbooks;
Excel.Workbook wb = wbs.Open(#"d:\test.xlsm");
Excel.Worksheet sheet = wb.ActiveSheet;
// set the view style
excel.ActiveWindow.View = XlWindowView.xlNormalView;
object filename = #"d:\test1.xlsm";
wb.SaveAs(filename);
wbs.Close();
excel.Quit();
if you have more Worksheets, you have to do that on each Worksheet...
I'm trying to create an script C# in SSIS to create a new column in a sheet on Excel.
I need to know the IndentLevel of a cell in excel and for this i have to create a new column with this values.
I'm trying to do this (Script in c#):
Range values = sheet.get_Range("A13");
values.Value = sheet.Range["B13"].IndentLevel();
In VBA Works like this (Script in VBA inside of a excell):
Range("A16").Value = Range("B16").IndentLevel
In C# how can i do that? i'm trying everything but doenst work.
Complete script:
xlApp = new _Excel.Application();
xlApp.Visible = true;
oWB = (_Excel.Workbook)xlApp.Workbooks.Open(destFile);
_Excel.Worksheet sheet = (_Excel.Worksheet)xlApp.Worksheets[1];
sheet.Columns["B:N"].Delete();
Range values = sheet.get_Range("A13");
values.Value = sheet.Range["B13"].IndentLevel();
Getting rid of the parenthesis seems to do the task correctly.
string destFile = #"E:\StackOverflow\Sample.xlsx";
var xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.Visible = true;
var oWB = (Microsoft.Office.Interop.Excel.Workbook)xlApp.Workbooks.Open(destFile);
Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)xlApp.Worksheets[1];
sheet.Range["A16"].Value = sheet.Range["B16"].IndentLevel;
The value in cell A16 is set to B16's indent level.
The only other note is to make sure that the file isn't open elsewhere, otherwise the code will open up a read-only copy.
I started creating an Excel-Add-IN with C#.
what I need to do is simple, I need to set a workbook to a variable, the workbook is already running, I tried this but did not work
Excel.Application excel = new Excel.Application();
Excel.Workbook wb = excel.ActiveWorkbook as Excel.Workbook;
wb.SaveAs("C:\\Users\\ro_sg\\Desktop\\Pasta1.xlsx");
Excel.Worksheet ws = wb.Worksheets["Plan1"];
Excel.Range range = ws.Range["A1"];
range.Value = "Success";
wb.Save();
The wb variable cannot find the workbook (gets null), and I can't see why.
Please, if any of you spot the mistake let me know.
Thanks!
I believe your issue is it may not be finding the active Excel application upstream from when you set your workbook variable. It appears that your code is trying to create a new excel application (without a workbook) rather than get the existing one that is open.
Give this a try:
Excel.Application excel = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
Excel.Workbook wb = (Excel.Workbook)excel.ActiveWorkbook;
wb.SaveAs("D:\\WeeeDueceDuece.xlsx");
I don't know if you need to get a specific Sheet but if you try this: Excel.Worksheet ws = wb.Worksheets[1]; It will get the first Sheet of your Workbook
If your actual code doesn't have more in-between steps, it will always fail. I'm surprised this line didn't error:
Excel.Workbook wb = excel.ActiveWorkbook as Excel.Workbook;
It's because a new instance of Excel does not necessarily create a new workbook. You can check this with the following lines:
Excel.Application application = new Excel.Application();
Excel.Workbooks workbooks = application.Workbooks;
Console.WriteLine(workbooks.Count); // "0"
The new workbook, however, should create the default number of worksheets (usually 3, but editable).
I have linked an application that gets data from an API, I open the sheet when a new contract is loaded to the program. Now I am trying to write new data to the excel sheet later in the program when i collect new data.
I know how to write data to the excel sheet and how to open the sheet I want to write on. The problem is I don't know how to write to the sheet once its already open, all I can get it to do is open another instance of the sheet.
I need to be able to open the sheet in one void and then update the now open sheet in a later void. How do I check to see if the sheet is open and if it is then access it again to write more data to it?
Here is how I have opened Excel,
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Console.WriteLine("Opening Excel...");
if (xlApp == null)
{
Console.WriteLine("EXCEL could not be started. Check that your office installation and project references are correct.");
return;
}
xlApp.Visible = true;
Workbook wb = xlApp.Workbooks.Open(#"C:\Users\Craig Key\Desktop\AppExports\TestExport.xlsx");
Console.WriteLine("Opening Currently Linked Workbook...");
Worksheet ws = (Worksheet)wb.ActiveSheet;
Console.WriteLine("Opening Active Worksheet...");
if (ws == null)
{
Console.WriteLine("Worksheet could not be created. Check that your office installation and project references are correct.");
}
Now later I need to find xlApp later in the program and write to it again, without opening another instance of the file.
I figured this out after searching for a while, I needed to use the marsh to try to bind the the open instance and then work with it.
Microsoft.Office.Interop.Excel.Application xlApp = null;
//Microsoft.Office.Interop.Excel.Workbooks wbs = null;
Microsoft.Office.Interop.Excel.Workbook wb = null;
Microsoft.Office.Interop.Excel.Worksheet ws = null;
bool wasFoundRunning = false;
Microsoft.Office.Interop.Excel.Application tApp = null;
//Checks to see if excel is opened
Console.WriteLine("CDC is looking for Excel...");
try
{
tApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
wasFoundRunning = true;
}
catch (Exception)//Excel not open
{
wasFoundRunning = false;
}
if (true == wasFoundRunning)
{
//Control Excel
}
I receive some reports in an xslx file that has 2 sheets, the data is good but there's no formatting done on the file. Most of the posts I found talk about formatting the file while creating it, but I'm wondering if there's a way I can work the file with c# code after receiving it (ex : fit columns to content)?
Thank you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClosedXML;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.CSharp;
using DocumentFormat.OpenXml.Office.Excel;
namespace ExcelFormatter
{
class MainScript
{
public static void Main(string[] args)
{
string file = args[0];
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
Excel.Range chartRange;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(file);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
chartRange = xlWorkSheet.get_Range("A1", "F1");
chartRange.Cells.Font.Bold = true;
xlWorkBook.Save();
xlWorkBook.Close(true, file, misValue);
xlApp.Quit();
}
}
}
I use ClosedXML to manipulate Excel files that have been created using the OpenXML standard. It found it to be easy to use and allowed me to do a lot of things to my documents. Hope this helps.
Wade
Here is an example of what I have done. It is in VB.Net, but you should be able to convert it with no problem.
'Open the workbook and then open the worksheet I want to work with.
Dim workbook = New XLWorkbook("<filepath>")
Dim worksheet = workbook.Worksheet("<worksheetname>")
' Throw an exception if there is no sheet.
If worksheet Is Nothing Then
Throw New ArgumentException("Sheet is missing")
End If
'Set number formatting. You can look at the closedxml documentation to see what the number should be
worksheet.Cell("G5").Style.NumberFormat.SetNumberFormatId(1)
'Merge and style a group of cells
Dim cellRange = "A1:A12"
worksheet.Range(cellRange).Merge.Value = colName
worksheet.Range(cellRange).Style.Fill.BackgroundColor = XLColor.Black
worksheet.Range(cellRange).Style.Font.FontColor = XLColor.White
worksheet.Range(cellRange).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center
'Auto adjust the column widths
worksheet.Columns.AdjustToContents()
workbook.SaveAs("<filename>")
You can use EasyXLS to import the xlsx file and after that to apply the format that you need:
// Create an instance of the class that imports XLSX files
ExcelDocument workbook = new ExcelDocument();
// Import XLSX file
workbook.easy_LoadXLSXFile(filePath);
// Get the table of data from the first sheet
ExcelTable xlsTable = ((ExcelWorksheet)workbook.easy_getSheetAt(0)).easy_getExcelTable();
// Create the formatting style for cells
ExcelStyle xlsStyle = new ExcelStyle();
xlsStyle.setHorizontalAlignment(Alignment.ALIGNMENT_LEFT);
xlsStyle.setForeground(Color.DarkGray);
//Apply the formatting to A1 cell
xlsTable.easy_getCell(0, 0).setStyle(xlsStyle);
// Resave the XLSX file
workbook.easy_WriteXLSXFile(newFormattedFilePath);
Check this link on formatting Excel cells fro more specific details.