I have a C# Winforms program that opens an excel document with the code below.
It works great but what I can not figure out how to do, is to turn off ALL menu's and toolbars.
The excel version I am using right now is 2003... But I will be upgrading to 2010 in the near future.
Any ideas?
//top of source...
using Excel = Microsoft.Office.Interop.Excel;
// Code inside a function...
// Get report and display it on the screen.
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open(strFileName, 0, true, 5, "", "", true,Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlApp.Visible = true;
xlApp.DisplayFullScreen = true;
// Display the Document and then Sleep.
System.Threading.Thread.Sleep(timeToShowMilliseconds);
// Close the Excel report
xlWorkBook.Close(false, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
I've been looking into your case and i think with Excel.Application you can find the answer.
Apparently what you need to do is something like this:
Excel.Application xlApp;
xlApp.CommandBars("tabName").Controls("File").Enabled = false;
try it and let me know, if it doesnt work we'll figure something out.
Related
So I am working in visual studio 2013 and I am trying to return the string in a given cell in a worksheet.
public StringBuilder MyCellData(int rCnt, int cCnt)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
StringBuilder str = new StringBuilder("");
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(#"C:\Users\james.naughton\Documents\Visual Studio 2013\Projects\QA_Automation\QA_Automation\copyChangeReportWAccountID.xlsx", 0, true, 5, "Landeck1", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets.get_Item(1);
range = xlWorkSheet.UsedRange[rCnt,cCnt];
str.Append((range.Item[rCnt, cCnt]).ToString());
return str;
Now whenever I run the program for some reason the values for range and xlWorkSheet are always COM Object, so when it is not returning what I want it to. Any suggestions on how to access the correct worksheet and return the data from a cell?
Thanks,
James
You need to get the Value of your cell:
str.Append((range.Item[rCnt, cCnt]).Value.ToString());
When exporting to excel I get blank or multiple rows per data source row when one of my data source cells contains a line break (Carriage Return). I want to prevent this.
This is the code I am using to create a workbook and paste in my data:
//Copy to clipboard
DGVJobList.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
DGVJobList.SelectAll();
DataObject DO = DGVJobList.GetClipboardContent();
Clipboard.SetDataObject(DO);
DGVJobList.ClearSelection();
//Create Excel Workbook and Paste
Excel.Application XLApp = new Excel.Application();
Excel.Workbook XLWorkBook;
Excel.Worksheet XLWorkSheet;
object misValue = System.Reflection.Missing.Value;
XLWorkBook = XLApp.Workbooks.Add(misValue);
XLWorkSheet = (Excel.Worksheet)XLWorkBook.Worksheets.get_Item(1);
Excel.Range XLRange = (Excel.Range)XLWorkSheet.Cells[1, 1];
XLRange.Select();
XLWorkSheet.PasteSpecial(XLRange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
Instead of using the clipboard, you will have more control over data placement by creating a 2D array of data out of your DGVJobList. Then, create a reference to the Excel Range of the same dimensions and set its value. This example shows only a generic 2D array for illustration. You would build your 2D array to lay out your data the way you want.
//Build data as 2D array
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
//Create Excel Workbook and Paste
Excel.Application XLApp = new Excel.Application();
Excel.Workbook XLWorkBook;
Excel.Worksheet XLWorkSheet;
object misValue = System.Reflection.Missing.Value;
XLWorkBook = XLApp.Workbooks.Add(misValue);
XLWorkSheet = (Excel.Worksheet)XLWorkBook.Worksheets.get_Item(1);
//Use range same size as data
Excel.Range XLRange = (Excel.Range) XLWorkSheet.Range["A1", "B4"];
XLRange.Value = array2D;
I tried almost everything that I could find here on StackOverflow but my code keeps throwing the following error:
Exception from HRESULT: 0x800A03EC
on the line with delete(). I was hoping you people could help me out.
Here's my current code
var xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook book =
xlApp.Workbooks.Open(File_name);
xlApp.DisplayAlerts = false;
Excel.Worksheet worksheet = (Excel.Worksheet)book.Worksheets[2];
worksheet.Delete();
book.Worksheets.Add();
xlApp.DisplayAlerts = true;
book.Save();
book.Close();
xlApp.Quit();
Marshal.ReleaseComObject(worksheet);
Marshal.ReleaseComObject(book);
Marshal.ReleaseComObject(xlApp);
And here's the other code i tried:
oXL.DisplayAlerts = false;
worksheet = (Excel.Worksheet)theWorkbook.Sheets[i];
((Excel.Worksheet)theWorkbook.Sheets[i]).Delete();
oXL.DisplayAlerts = true;
oWB.Save();
oWB.Close(false, missing, missing);
oSheet = null;
oWB = null;
oXL.Quit();
And some more variations
Microsoft.Office.Interop.Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook oWB;
Excel.Worksheet oSheet;
Excel.Workbooks oMWB;
and i'm using this reference:
using Excel = Microsoft.Office.Interop.Excel;
Working with the Excel Interop libraries, I encountered this error many times. The main cause of this problem (a generic COM exception), most of the times, is that Excel tries to find something you've asked for, but Excel isn't able to find it. See this answer, it helped me a lot.
Reading these lines:
Excel.Worksheet worksheet = (Excel.Worksheet)book.Worksheets[2];
worksheet.Delete();
I think that you're trying to delete a worksheet that's not existing. Check your Excel document.
I just made the most stupid mistake ever..... the excel file was a shared file, that's why i couldn't delete it..
Sorry for making such a stupid mistake, and thanks to everybody who tried to help me!
HRESULT: 0x800A03EC is an unknown COM error. This usually happens when Excel throws some error because your input or parameters were wrong.
This example provide msdn: Programmatically Deleting Worksheets from Workbooks
((Excel.Worksheet)this.Application.ActiveWorkbook.Sheets[4]).Delete();
So try next:
Excel.Worksheet worksheet = (Excel.Worksheet)book.Sheets[2];
worksheet.Delete();
instead of:
Excel.Worksheet worksheet = (Excel.Worksheet)book.Worksheets[2];
worksheet.Delete();
Try this:
xlApp.DisplayAlerts = false;
Excel.Worksheet worksheet = (Excel.Worksheet)book.Worksheets[2];
worksheet.Delete();
xlApp.DisplayAlerts = true;
Also important to keep in mind, interop starts to count from 1, not from 0. so deleting item [0] or deleting the only sheet will throw you an exception. if you plan to remove the [2] worksheet, the third one will take its place. So make sure to remove from the last to the first.
this is code i have used to delete the excel sheet
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
return;
}
xlApp.DisplayAlerts = false;
string filePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
+ "\\Sample.xlsx";
Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(filePath, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
Excel.Sheets worksheets = xlWorkBook.Worksheets;
worksheets[4].Delete();
worksheets[3].Delete();
xlWorkBook.Save();
xlWorkBook.Close();
releaseObject(worksheets);
releaseObject(xlWorkBook);
releaseObject(xlApp);
and use this
static void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
throw ex;
}
finally
{
GC.Collect();
}
}
I am using Excel Interop to work with some excel sheets. In a worksheet, I need to iterate through the rows, and if the first cell in the row is empty then I need to delete the entire row iteself. I tried the following-
Excel.Range excelRange = sheet.UsedRange;
foreach (Excel.Range row in excelRange.Rows)
{
String a = ((Excel.Range)row.Cells[Type.Missing, 1]).Value2 as String;
if (a == null || a == "")
{
((Excel.Range)row).Delete(Type.Missing);
}
}
This was not working at all. Is there any different way to do this?
And, is there any quick way to find and remove all formula in a Worksheet?
Let's say your Excel file looks like this.
The best way to delete rows would be to use Excel's inbuilt feature called Autofilter which will filter Col A for blank values and then deleting the entire rows in one go.
TRIED AND TESTED (In VS 2010 Ultimate)
Note: I have changed few lines which I feel could error out in VS 2008. Since I don't have VS 2008, I couldn't test it there. If you get any errors do let me know and I will rectify it.
//~~> Open File
private void button1_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application xlexcel;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
Microsoft.Office.Interop.Excel.Range xlRange;
Microsoft.Office.Interop.Excel.Range xlFilteredRange;
xlexcel = new Excel.Application();
xlexcel.Visible = true;
//~~> Open a File
xlWorkBook = xlexcel.Workbooks.Open("C:\\MyFile.xlsx", 0, false, 5, "", "", true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
//~~> Work with Sheet1
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//~~> Get last row in Col A
int _lastRow = xlWorkSheet.Cells.Find(
"*",
xlWorkSheet.Cells[1,1],
Excel.XlFindLookIn.xlFormulas,
Excel.XlLookAt.xlPart,
Excel.XlSearchOrder.xlByRows,
Excel.XlSearchDirection.xlPrevious,
misValue,
misValue,
misValue
).Row ;
//~~> Set your range
xlRange = xlWorkSheet.Range["A1:A" + _lastRow];
//~~> Remove any filters if there are
xlWorkSheet.AutoFilterMode=false;
//~~> Filter Col A for blank values
xlRange.AutoFilter(1, "=", Excel.XlAutoFilterOperator.xlAnd, misValue, true);
//~~> Identigy the range
xlFilteredRange = xlRange.Offset[1,0].SpecialCells(Excel.XlCellType.xlCellTypeVisible,misValue);
//~~> Delete the range in one go
xlFilteredRange.EntireRow.Delete(Excel.XlDirection.xlUp);
//~~> Remove filters
xlWorkSheet.AutoFilterMode = false;
//~~> Close and cleanup
xlWorkBook.Close(true, misValue, misValue);
xlexcel.Quit();
releaseObject(xlRange);
releaseObject(xlFilteredRange);
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();
}
}
Output
I have created the sheet1 and populated some data in the sheet, using the data from sheet1 i want to create a chart sheet with ploting the data
try
{
app = new Excel.Application();
app.Visible = true;
workbook = app.Workbooks.Add(1);
worksheet = (Excel.Worksheet)workbook.Sheets[1];
PopulateDateInExcel(pathtologsfolder, startdate, enddate);
// create a chart
Excel.Range chartRange;
object misValue = System.Reflection.Missing.Value;
Excel.ChartObjects xlCharts = (Excel.ChartObjects)worksheet.ChartObjects(Type.Missing);
Excel.ChartObject myChart = (Excel.ChartObject)workbook.Charts[2];
Excel.Chart chartPage = myChart.Chart;
chartRange = worksheet.get_Range("AN1", "AP6");
chartPage.SetSourceData(chartRange, misValue);
chartPage.ChartType = Excel.XlChartType.xl3DLine;
}
catch (Exception e)
{
//Console.Write("Error");
}
finally
{
}
Thanks in advance,
Excel Automation
Try this (UNTESTED)
Excel.ChartObject myChart = (Excel.ChartObject)charts.Add(10, 70, 250, 250);
instead of
Excel.ChartObject myChart = (Excel.ChartObject)workbook.Charts[2];
and then once your chart is created, move it to a chart sheet using this code
chart.Location(XlChartLocation.xlLocationAsNewSheet, Type.Missing);
The way to do this would be to use the Add method:
Excel.Workbook xlWorkbook;
Excel.Chart chartName = (Excel.Chart)xlWorkbook.Charts.Add();
Admittedly, at least in my experiments this causes trouble as the dataset it is using by default is fairly random (Excel magic...) so you might be needing to reformat it afterwards (delete and add datasets, etc), but that's the method to do it.
EDIT:
I should note that Excel support documentation seems to recommend the Add2 method method, but I haven't managed to use it successfully:
Excel.Workbook xlWorkbook;
Excel.Chart chartName = (Excel.Chart)xlWorkbook.Charts.Add2();
Excel.Application oXL = new Excel.Application();
and after then
oXL.Run() and see attached: