I have tried a few options but none seem to work, and some send errors.
Please let me know what I am doing wrong
public string Main(String wbPath, String wbName)
{
string cName = "";
Excel.Application xlApp;
Excel.Workbook xlWB;
Excel.Worksheet xlWS;
xlApp = new Excel.Application();
xlApp.DisplayAlerts = false;
xlApp.Calculation = Excel.XlCalculation.xlCalculationManual; //Error occurs here
xlWB = xlApp.Workbooks.Open(wbPath + wbName);
xlWB.SaveAs("vFile.html", Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml);
cName = xlWB.FullName;
xlWB.Close();
xlApp.Quit();
return cName;
}
Error code:
{"Exception from HRESULT: 0x800A03EC"}
You must open the workbook before setting the xlApp.Calculation:
static void Main(string[] args)
{
string cName = "";
var xlApp = new Application();
var xlWB = xlApp.Workbooks.Open("youpathgoeshere", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlApp.Calculation = XlCalculation.xlCalculationManual;
var xlWS = new Worksheet();
xlWB.SaveAs("vFile.html", Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml);
cName = xlWB.FullName;
xlWB.Close();
xlApp.Quit();
}
You can try this solution:
This example causes Microsoft Excel to calculate workbooks before they are saved to disk.
Excel.Application xlApp;
xlApp = new Excel.Application();
Application.Calculation = xlCalculationManual
Application.CalculateBeforeSave = True
Related
The code here grabs a name in my listbox(employeebox) and deletes the entire row on that sheet. This works and there are no errors.. My problem is that I have 19 different sheets that need to be checked, but I can only check 1 at a time with this code.. "Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets[2];".. Is there any way that I can check all the sheets once the Delete button is clicked? I greatly appreciate anyone's help.
private void delete_Click(object sender, EventArgs e)
{
//create excel
Excel.Application xlexcel = new Excel.Application();
Excel.Workbook xlWorkBook = xlexcel.Workbooks.Open(#"C:\\SAMPLE.xlsx");
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets[2];
//search within excel
Excel.Range usedRanage = xlWorkSheet.UsedRange;
foreach (Excel.Range row in usedRanage)
{
//grab name once selected in box
if (employeeBox.SelectedItem.Equals(row.Value))
{
row.EntireRow.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);
MessageBox.Show("Employee Deleted.");
}
}
xlexcel.DisplayAlerts = false;
xlWorkBook.SaveAs("C:\\SAMPLE.xlsx", Excel.XlFileFormat.xlWorkbookDefault, Type.Missing,
Type.Missing, false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlWorkBook.Close();
xlexcel.Quit();
releaseObject(xlexcel);
releaseObject(xlWorkBook);
releaseObject(xlWorkSheet);
}
private void delete_Click(object sender, EventArgs e)
{
//create excel
Excel.Application xlexcel = new Excel.Application();
Excel.Workbook xlWorkBook = xlexcel.Workbooks.Open(#"C:\\SAMPLE.xlsx");
int[] Cols = { 1 };
Excel.Range curRange;
foreach (Excel.Worksheet sheet in xlWorkBook.Worksheets)
{
foreach (Excel.Range row in sheet.UsedRange.Rows)
{
foreach (int c in Cols)
{
curRange = (Excel.Range)row.Cells[1, 1];
if (curRange.Cells.Value != null)
{
if (employeeBox.SelectedItem.Equals(sheet.Cells[row.Row, c].Value.ToString()))
{
row.EntireRow.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);
MessageBox.Show("Employee Deleted.");
}
}
}
}
}
xlexcel.DisplayAlerts = false;
xlWorkBook.SaveAs("C:\\SAMPLE.xlsx", Excel.XlFileFormat.xlWorkbookDefault, Type.Missing,
Type.Missing, false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlWorkBook.Close();
xlexcel.Quit();
releaseObject(xlexcel);
releaseObject(xlWorkBook);
}
I have a datagridview in my windowsforms project and I can export it to an Excel file like as:
private void btnExcel_Click(object sender, EventArgs e)
{
copyAlltoClipboard();
Microsoft.Office.Interop.Excel.Application xlexcel;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlexcel = new Microsoft.Office.Interop.Excel.Application();
xlexcel.Visible = true;
xlWorkBook = xlexcel.Workbooks.Open("C:\\file.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[12, 3];
CR.Select();
xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
}
private void copyAlltoClipboard()
{
dataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
dataGridView1.MultiSelect = true;
dataGridView1.SelectAll();
DataObject dataObj = dataGridView1.GetClipboardContent();
if (dataObj != null)
Clipboard.SetDataObject(dataObj);
}
I update the datagridview data by a button click. I want to copy these all of datagridview data and paste them to the same excel file sheet. Of course cell ranges should change. How can I do?
I don't use C# - here is a VB.Net version:
Use the C# version of Imports Microsoft.Office.Interop to save some typing.
In the OP the Dim CR... set the destination range. I added a second paste with a different range.
The code operates on the range directly instead of using the current selection. When you record macros the generated code operates on the selection but your code can define a range and operate on it directly.
Imports Microsoft.Office.Interop
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
copyAlltoClipboard(dgv)
Dim xlexcel As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
xlexcel = New Excel.Application
xlexcel.Visible = True
xlWorkBook = xlexcel.Workbooks.Open("C:\temp\file.xlsx")
xlWorkSheet = xlWorkBook.Worksheets(1)
Dim CR As Excel.Range = xlWorkSheet.Cells(12, 3)
CR.PasteSpecial()
' change range and paste again
CR = xlWorkSheet.Cells(1, 3)
CR.PasteSpecial()
End Sub
I am trying to export to excel from my Datagrid. The Datagrid has a column where we put comments in. In that column the comments are put on separate lines. When it exports to excel it exports in multiple rows.
Here is how it looks in my DataGrid:
Here is how it looks when I export to Excel:
Here is the code that I am using to do it:
public static void CreateExcelFromClipboard(string worksheetName, string fullFilePath, bool toOpen)
{
//Excel Application class
_Application app = new Microsoft.Office.Interop.Excel.Application();
//Get process id
int excelProcessId = GetApplicationProcessId(app);
try
{
//Add workbook
Workbook theWorkbook = app.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
//Add worksheet
var theWorksheet =
(Worksheet)theWorkbook.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
theWorksheet.Name = worksheetName;
app.SheetsInNewWorkbook = 1;
app.DisplayAlerts = false;
theWorksheet.Activate();
//Paste to the worksheet from clpboard
theWorksheet.Paste(Type.Missing, Type.Missing);
//Apply Borders
ApplyBorder(theWorksheet.UsedRange);
//Auto Fit All columns
Range xlRange = theWorksheet.UsedRange;
// put all hardcodes in a constant class
xlRange.Font.Name = "Arial";
xlRange.Font.Size = 9;
var firstRowRange = (Range)xlRange.Rows[1, Missing.Value];
firstRowRange.EntireRow.Font.Bold = true;
firstRowRange.EntireRow.HorizontalAlignment = XlHAlign.xlHAlignCenter;
//Set Wrap Test to false
xlRange.WrapText = true;
xlRange.Columns.AutoFit();
theWorksheet.Activate();
//Save the file
theWorkbook.SaveAs(fullFilePath, XlFileFormat.xlOpenXMLWorkbook, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
if (!toOpen)
{
//Clean up
app.Quit();
Marshal.ReleaseComObject(app);
}
}
catch
{
ForceExcelClose(excelProcessId);
throw;
}
finally
{
app.Visible = toOpen;
}
}
I know we can open a particular worksheet of MS Excel using C# by providing the sheet number (1,2,3..) or name (sheet1, sheet2, sheet3...)
I have a excel file which has 2 sheets, 1. Values, 2. Results
Is there a way to open a sheet giving the sheet name ,i.e, "Values" instead of 1 or [s|S]heet1 in C# ??
I looked thru the old posts but didnt find anything useful...
so again, what I am trying to do is, open a Excel worksheet by using its user defined name (Values) instead of the system defined name(1 or [s|S]heet1)
any inputs would be greatly appreciated!
Add reference to Microsoft.Office.Interop.Excel in your project and you can use next code as base
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
//Start Excel and get Application object.
oXL = new Excel.Application();
oXL.Visible = false;
oXL.DisplayAlerts = false; // prevents message from popping up
try
{
//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Open(filename, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
int nCounter = 1;
oSheet.Copy(oSheet, Type.Missing);
Excel._Worksheet oSheetGame = (Excel._Worksheet)oWB.Worksheets["MyTemplate"];
oSheetGame.Name = "MyNewWorksheetName";
// do something with worksheet
((Excel._Worksheet)oWB.Sheets["MyTemplate"]).Delete(); // delete template
((Excel._Worksheet)oWB.Worksheets["MyNewWorksheetName"]).Activate();
}
catch (Exception e)
{
//throw e;
throw;
}
finally
{
//Make sure Excel is visible and give the user control
//of Microsoft Excel's lifetime.
oXL.Visible = true;
oXL.UserControl = true;
}
oXL.Save(Type.Missing);
#volody, thanks! your post helped a lot.
I took the worksheet declaration part from yours and changed mine into following:
Excel.Application excelApplication;
Excel.Worksheet excelWorksheet;
Excel.Workbook excelWorkbook;
Excel.Range range;
excelApplication = new Excel.Application();
excelWorkbook = (Excel.Workbook)(excelApplication.Workbooks.Open(
<FILENAME>,
Type.Missing, true, Type.Missing, Type.Missing, Type.Missing,
true, Type.Missing, Type.Missing, false, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing));
excelWorksheet = (Excel.Worksheet)excelWorkbook.Worksheets[<WORKSHEETNAME>];
The code above helps in opening a Excel Worksheet with a User defined name. For example, to open a Worksheet named Test instead of Sheet1.
Ivar
I know we can open a particular worksheet of MS Excel using C# by providing the sheet number (1,2,3..) or name (sheet1, sheet2, sheet3...)
I have a excel file which has 2 sheets, 1. Values, 2. Results
Is there a way to open a sheet giving the sheet name ,i.e, "Values" instead of 1 or [s|S]heet1 in C# ??
I looked thru the old posts but didnt find anything useful...
so again, what I am trying to do is, open a Excel worksheet by using its user defined name (Values) instead of the system defined name(1 or [s|S]heet1)
any inputs would be greatly appreciated!
Add reference to Microsoft.Office.Interop.Excel in your project and you can use next code as base
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
//Start Excel and get Application object.
oXL = new Excel.Application();
oXL.Visible = false;
oXL.DisplayAlerts = false; // prevents message from popping up
try
{
//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Open(filename, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
int nCounter = 1;
oSheet.Copy(oSheet, Type.Missing);
Excel._Worksheet oSheetGame = (Excel._Worksheet)oWB.Worksheets["MyTemplate"];
oSheetGame.Name = "MyNewWorksheetName";
// do something with worksheet
((Excel._Worksheet)oWB.Sheets["MyTemplate"]).Delete(); // delete template
((Excel._Worksheet)oWB.Worksheets["MyNewWorksheetName"]).Activate();
}
catch (Exception e)
{
//throw e;
throw;
}
finally
{
//Make sure Excel is visible and give the user control
//of Microsoft Excel's lifetime.
oXL.Visible = true;
oXL.UserControl = true;
}
oXL.Save(Type.Missing);
#volody, thanks! your post helped a lot.
I took the worksheet declaration part from yours and changed mine into following:
Excel.Application excelApplication;
Excel.Worksheet excelWorksheet;
Excel.Workbook excelWorkbook;
Excel.Range range;
excelApplication = new Excel.Application();
excelWorkbook = (Excel.Workbook)(excelApplication.Workbooks.Open(
<FILENAME>,
Type.Missing, true, Type.Missing, Type.Missing, Type.Missing,
true, Type.Missing, Type.Missing, false, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing));
excelWorksheet = (Excel.Worksheet)excelWorkbook.Worksheets[<WORKSHEETNAME>];
The code above helps in opening a Excel Worksheet with a User defined name. For example, to open a Worksheet named Test instead of Sheet1.
Ivar