According to the documentation of Workbook.Range, you can provide commas in the first argument to provide an union.
However, the following code throws a COMException with HRESULT 0x800A03EC on the line that gets the range:
using Microsoft.Office.Interop.Excel;
public void RangeWithCommas() {
var excel = new Application();
var wb = excel.Workbooks.Add(xlWBATemplate.xlWBATWorksheet);
var ws = (Worksheet)wb.Worksheets[1];
var range = ws.Range["A1,A2"]; // this throws an exception
Console.WriteLine(range.Address[false,false]);
ws.Delete();
wb.Close(false);
excel.Quit();
}
How can I do or fix this?
P.S. I am aware of Application.Union but I would very much prefer not to use it because there is no easy way to provide a variable number of arguments.
As AnalystCave.com pointed out, some Excel COM methods are locale specific. You need to use the regional list seperator when accessing the COM method.
This code should work correctly on all locales:
using Microsoft.Office.Interop.Excel;
public void RangeWithCommas() {
var excel = new Application();
var wb = excel.Workbooks.Add(xlWBATemplate.xlWBATWorksheet);
var ws = (Worksheet)wb.Worksheets[1];
var rangestring = String.Join((string)excel.International[XlApplicationInternational.xlListSeparator], new [] {"A1","A2"});
var range = ws.Range[rangestring];
Console.WriteLine(range.Address[false,false]);
ws.Delete();
wb.Close(false);
excel.Quit();
}
Related
I have a document that I need to update on a monthly basis and I'm writing an automation to do so. This is my first time attempting to update a document with C# as opposed to simply creating a new one. I have researched and tried implementing a few libraries that I've found online and here on StackOverflow, for example, ClosedXML, but so far I've had no luck. I understand this question has been asked here before, so my actual question is: Is my implementation incorrect/am I doing something wrong?
public void WriteToReport(List<BrandData> brandData, string reportFilePath)
{
using (var workbook = new XLWorkbook(reportFilePath))
{
var worksheet = workbook(1);
worksheet.Cell(26, 2).Value = "Hello World!";
workbook.SaveAs(reportFilePath);
}
}
Above is how I've tried to test ClosedXML so far. The GitHub docs imply that it should be this simple, but I don't see any changes made to the doc when the automation is finished. I've also tried using Streamwriter. If anyone can help me with ClosedXML or suggest another library that worked for them, it would be greatly appreciated.
Edit: Following explanations on other similar questions on here, I have tried this:
public void WriteToReport(List<BrandData> brandData, string reportFilePath)
{
var workbook = new XLWorkbook(reportFilePath);
var worksheet = workbook.Worksheet(1);
int numberOfLastColumn =
worksheet.LastColumnUsed().ColumnNumber();
IXLCell newCell = worksheet.Cell(numberOfLastColumn + 1, 1);
newCell.SetValue("Hello World");
workbook.SaveAs(reportFilePath);
}
Here is a simple example to write a string value to the first WorkSheet.
public void WriteToCell(string fileName, int row, int col, string value)
{
using var workbook = new XLWorkbook(fileName);
var worksheet = workbook.Worksheets.Worksheet(1);
worksheet.Cell(row, col).Value = value;
workbook.SaveAs(fileName);
}
I'm working on a program that allows the user to pull up part numbers from a database. The part numbers are then to be pasted into an active Excel Sheet.
I'm trying to do this with Excel interop Excel 16.0. I can copy the data but am having issues getting it to paste into excel.
private void cmdCopyToExcel_Click(object sender, EventArgs e)
{
string wb = cmb_BookName.Text.ToString();
string ws = cmb_SheetName.Text.ToString();
if (chkContainer.Checked)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks[wb];
Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[ws];
xlWorksheet.Cells[48, 4] = cboContainer.Text;
}
I'm able to get the open excel workbook and worksheet that I need, but when I try to paste it into excel all I get is a COM Exception. The exception occurs on line 10. I've tried using ("wb name") and ("ws name"), have also tried using index numbers [1] for workbook and [3] for worksheets but nothing works.
Can anyone see what I'm doing wrong or is there an easier way to copy from C# and paste into an excel cell?
Addition:I tried opening the workbook that I wanted to add test to, just to see if I could get it to work.
Here is the code:
private void button1_Click(object sender, EventArgs e)
{
try
{
//create a instance for the Excel object
Excel.Application oExcel = new Excel.Application();
//specify the file name where its actually exist
string filepath = #"K:\R&D Dept\Development Lab\R&D Test Request System (For testing and training)\Test Matrices\JRD Test Matrix for part numbers.xlsm";
//pass that to workbook object
Excel.Workbook WB = oExcel.Workbooks.Open(filepath);
// statement get the workbookname
string ExcelWorkbookname = WB.Name;
// statement get the worksheet count
int worksheetcount = WB.Worksheets.Count;
Excel.Worksheet wks = (Excel.Worksheet)WB.Worksheets[3];
// statement get the firstworksheetname
string firstworksheetname = wks.Name;
//statement get the first cell value
var firstcellvalue = ((Excel.Range)wks.Cells[48, 4]).Value;
}
catch (Exception ex)
{
string error = ex.Message;
}
}
}
}
This worked, so I guess my question becomes how to work with an Excel workbook and worksheet that are already open?
I would start by getting a range of cells: i.e.{Range test = {yourWorksheet}.Cells[RowNumber, ColumnNumber]}
Once you have that, you can set the value of that cell by calling the value, or value2 property like so: {test.Value or test.Value2 = {yourPastedData}}
we are trying to retrieve a calculated value from a cell which has add-In formulas in it.
The sample add-in "myUtilityl.xla" is working properly in excel. It retrieves value for the addin function =ISOWEEKNUM(F9). But we are unable to retrieve the value programatically using C# & Microsoft Object Library. The add-In "myUtilityl.xla" is attached to Excel. Environment is VS2010
I am providing the sample code here.
string path = #"C:\Test.xls";
Workbook theWorkbook;
Worksheet theWorksheet;
Range readRange;
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
theWorkbook = app.Workbooks.Open(path);
Sheets theSheets = (Sheets)theWorkbook.Worksheets;
theWorksheet = (Worksheet)theWorkbook.Worksheets.get_Item("Sheet1");
readRange = theWorksheet.get_Range("B1");
MessageBox.Show(Convert.ToString(readRange.Value));
//theWorkbook.Save();
app.Workbooks.Close();
I am new to Microsoft Object library. Any help or clue will be very helpful.
Well Brijesh its working now. The only thing that was missing was that we have to open the xla.
app.Workbooks.Open(xlaFilePath);
Then it started working..
Thank you very much. i am posting the code here anyways
string path = #"C:\Test2.xls";
string xlaPath = #"C:\Test2.xla";
Workbook theWorkbook;
Worksheet theWorksheet, theWorksheet2;
Range readRange;
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
app.Workbooks.Open(xlaPath);
theWorkbook = app.Workbooks.Open(path);
theWorksheet2 = (Worksheet)theWorkbook.Worksheets.get_Item("Sheet2");
theWorksheet2.get_Range("A3").Value = 7;
theWorksheet2.get_Range("A4").Value = 7;
theWorkbook.RefreshAll();
theWorksheet = (Worksheet)theWorkbook.Worksheets.get_Item("Sheet1");
readRange = theWorksheet.get_Range("A1");
Console.WriteLine(Convert.ToString(readRange.Value));
Console.ReadLine(); //theWorkbook.Save();
theWorkbook.Close();
app.Workbooks.Close();
Above code inputs two values into cells of sheet2 and the VBA UDF calculated value is retrieved.
you may add following in your code sample
var addins = Application.AddIns.Add(xlaFilePath);
if (!addins.Installed)
{
addins.Installed = true;
}
Everywhere I look for how to use excel function inside of a C# application tells me to do the following:
From the COM TabAdd the following using statement:using IExcel = Microsoft.Office.Interop.Excel
Then declare and initialise a IWorkSheetFunction objectIExcel.IWorksheetFunction iwf = new IExcel.IWorksheetFunction();
Now you can use the functions as in int result = iwf.Math.Sum(1,2);
The problem im having is that while intellisense is detecting IExcel, it is not showing IWorksheetFunction. It is however showing WorksheetFunction. Either way, it is not letting me instantiate it as an object. I am getting the error: Cannot create an instance of the abstract class or interface 'Microsoft.Office.Interop.Excel.WorksheetFunction'
any ideas?
Try:
Microsoft.Office.Interop.Excel.Application xl = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.WorksheetFunction wsf = xl.WorksheetFunction;
int result = wsf.Percentile(obj, 0.75);
Basically it comes down to, instead of:
IExcel.IWorksheetFunction iwf =
new IExcel.IWorksheetFunction(); // You can't instantiate an interface
use the WorksheetFunction property in Excel.Application:
IExcel.IWorksheetFunction iwf = xl.WorksheetFunction;
Its a function off the application object.
using Microsoft.Office.Interop.Excel;
static void Main(string[] args)
{
Application a = new Application();
double x = a.WorksheetFunction.Sum(1, 2);
Console.WriteLine("Sum = {0}", x);
}
I am attempting what seems like a simple task: using C# to create a new Excel document containing new worksheets.
For some reason, I am getting a strange COM error (0x800A03EC)
Has anyone managed to get this to work? Does anyone have suggestions as to how to troubleshoot this?
I've isolated this into the minimum amount of code:
using Microsoft.Office.Interop.Excel;
using System.Diagnostics;
namespace ExcelAutomation
{
public static class ExcelTests
{
public static void CreateWorksheet()
{
try
{
var app = new Microsoft.Office.Interop.Excel.Application();
app.Visible = true;
var workBooks = app.Workbooks;
var newWorkbook = app.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet existingWorksheet = (Worksheet)newWorkbook.Sheets[1];
Worksheet workSheet = (Worksheet)newWorkbook.Sheets.Add
(
null, // before
existingWorksheet,
null, // 1,
null //XlSheetType.xlWorksheet
);
}
catch (System.Runtime.InteropServices.COMException ex)
{
Trace.WriteLine(string.Format("Caught COMException. Message: \"{0}\"", ex.Message));
}
}
}
}
The output window now says:
Caught COMException. Message: "Exception from HRESULT: 0x800A03EC"
The mistake I'm making is to use null for optional values that I don't want to set.
Instead I should use System.Reflection.Missing.Value
Worksheet workSheet = (Worksheet)newWorkbook.Sheets.Add
(
existingWorksheet, // before
System.Reflection.Missing.Value,
System.Reflection.Missing.Value, // 1,
System.Reflection.Missing.Value //XlSheetType.xlWorksheet
);
I Think this will help you
Visit http://www.aspose.com/docs/display/cellsnet/Adding+New+Worksheets+to+Workbook+and+Activating+a+Sheet