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.
Related
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 am writing an Excel app in C# which does some data visualization. The first stage of the analysis is to copy the data from a single sheet in an input workbook to a new sheet in an output workbook where the analysis is performed.
This runs correctly on my laptop but when the client I am producing the code for runs the same application, they get some extra worksheets created which cause the code to crash.
It's pretty difficult to debug the application on the client's PC so I am having difficultly understanding how it's possible the results are different on two different machines.
Setup code is below, any help at all would be incredibly useful. Using Microsoft.Office.Interop.Excel 14.
Excel.Workbooks wbs = excelApp.Workbooks;
Excel.Workbook dataSource = wbs.Open(inFile);
//get the data sheet from the source file
Excel.Sheets dataSourceSheets = dataSource.Worksheets;
Excel.Worksheet dataSourceSheet = (Excel.Worksheet)dataSourceSheets.get_Item(1);
//create a new workbook
dataOutput = wbs.Add();
outputSheets = dataOutput.Worksheets;
//ensure there are only 2 sheets in the output
int osc = outputSheets.Count;
for (int i = 2; i < osc; ++i)
{
outputSheets.get_Item(i).Delete();
}
//setup summary and contents pages
summaryPage = outputSheets.get_Item(1);
summaryPage.Name = "Summary";
contentsPage = outputSheets.Add(Type.Missing, summaryPage);
contentsPage.Name = "Contents";
dataSourceSheet.Copy(Type.Missing, contentsPage); //copy the sheet AFTER contents page
dataSheet = (Excel.Worksheet)outputSheets.get_Item(outputSheets.Count);
dataSheet.Name = "Raw Data";
//fails with outputSheets.Count == 5
if (outputSheets.Count != 3)
{
throw new Exception("Error, there are too many sheets here!");
}
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#
I am trying to do the following using c# code:
Hide some rows in excel.
Clear all data and formats in excel sheet.
Put other data to excel sheet.
I would like the hidden rows still remain hidden.
Is it possible?
Thank You!
I've had great results using ClosedXML to manipulate excel spreadsheets.
While I haven't tried your case I've done similar things. In my case I put my private data into a new worksheet and hide that, which ClodedXML made simple.
Here's a sample code that can get you going....
//Create an Excel App
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook xlWorkBook = null;
Microsoft.Office.Interop.Excel._Worksheet xlWorksheet;
//Open a Workbook
xlWorkBook = xlApp.Workbooks.Open(#"d:\test.xlsx");
xlWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Sheets[1];
//My Workbook contains 10 rows with some data and formatting
//I Hide rows 3, 4 & 5
Microsoft.Office.Interop.Excel.Range hiddenRange = xlWorksheet.get_Range("A3:C5");
hiddenRange.EntireRow.Hidden = true;
//Get the entire sheet and Clear everything on it including data & formatting
Microsoft.Office.Interop.Excel.Range allRange = xlWorksheet.UsedRange;
allRange.Clear();
//Now Add some new data, say a Title on the first cell, and some more data in a loop later
xlWorksheet.Cells[1, 1] = "Title";
for (int i = 6; i < 10; i++)
{
xlWorksheet.Cells[i, 1] = i.ToString();
}
xlApp.Visible = true;
Thats it....
Store them in a variable and hide them again after you have populated excel with data.
I am trying to an Add-in directly from C# so that when I open a workbook, and do a Workbook.Calculate() the UDF's (User Defined Functions) that are defined in an external addin correctly calculate in the worksheet. Currently, I am looping through each adding and simple setting:
AddIn.Installed = true
This does not work. C# does not load add-in at all, and I want to avoid using VBA. I want to open a workbook an excel workbook with the specific add in loaded, do a full calculated, and should have all values of the worksheet updated, including cells with UDF's.
Thanks for any help....
Some code:
Excel.Workbook wkbk = ExcelApp.ActiveWorkbook;
Excel.XlFixedFormatType paramExportFormat = Excel.XlFixedFormatType.xlTypePDF;
Excel.XlFixedFormatQuality paramExportQuality = Excel.XlFixedFormatQuality.xlQualityStandard;
bool paramOpenAfterPublish = false;
bool paramIncludeDocProps = true;
bool paramIgnorePrintAreas = true;
object paramFromPage = Type.Missing;
object paramToPage = Type.Missing;
ExcelApp.Visible = true;
//foreach (Excel.AddIn aiTemp in ExcelApp.AddIns)
//{
// if (aiTemp.Name.Contains(""))
// {
// aiTemp.Installed = false;
// aiTemp.Installed = true;
// }
//}
while (ExcelApp.CalculationState == Microsoft.Office.Interop.Excel.XlCalculationState.xlCalculating)
{
Thread.Sleep(50);
}
ExcelApp.CalculateFull();
var wksht = wkbk.ActiveSheet;
Excel.Range rng = ((Excel.Worksheet)wksht).get_Range("B1", "B1");
rng.Calculate();
//EnsureCalcFinished();
ExcelApp.Visible = false;
wkbk.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, PathToDocument.Replace(".xlsx", ".pdf"), paramExportQuality, true, false, Type.Missing, Type.Missing, true,Type.Missing);
UPDATE:
I found a link with the method I use to register UDFs.
Ref: http://msdn.microsoft.com/en-us/library/ms173189(v=vs.80).aspx
In Excel, you need to go to Options -> Add-Ins => Excel Add-in (Go..) => automation = select the library and hit OK. Once you do this once, it'll be auto-loaded each time you open excel.
Here is the algorithm to load excel AddIns so that when you open excel workbook, a calculation will include UDF's defined in Add-in:
1)Initiliaze Excel Application
ExcelApp = new Excel.Application();
2)Load AddIns *
foreach (Excel.AddIn ai in ExcelApp.AddIns)
{
ai.Installed = false;
ai.Installed = true;
ExcelApp.Wait(50);
}
**The Key is to load add-ins before you open Excel Workbook.
3)Open Excel Workbook, which will trigger calculations
4)Set Calculation Mode to manual so that any changes in Interop do not trigger lengthy recalc
ExcelApp.Calculation = Microsoft.Office.Interop.Excel.XlCalculation.xlCalculationManual;
5)Perform any manipulations, and perform calc
ExcelApp.CalculateFull();
6)Dispose of Excel Objects appropriately
Hope this helps someone with a similar issue.. Ended up being a simple fix for a simple problem. Just remember to load add-ins before opening the workbook. Otherwise, opening an excel workbook with UDF's dependent on AddIn will fail.