First i apologize for the mistakes in my text, english is not my native language and i do my best.
I'm a very beginner in coding and i have a little question about loading an excel sheet.
I'm trying to do a project with vb in c# and i have to load an excel sheet which already exist and write in it. I found some explanations who help me to create a New sheet and write in it :
private void button1_Click(object sender, System.EventArgs e)
{
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;
try
{
oXL = new Excel.Application("Exemple.xlsx");
oXL.Visible = true;
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
oSheet.Cells[1, 1] = "First Name";
oSheet.Cells[1, 2] = "Last Name";
oSheet.Cells[1, 3] = "Full Name";
oSheet.get_Range("A1", "C1").Font.Bold = true;
oSheet.get_Range("A1", "C1").VerticalAlignment =
Excel.XlVAlign.xlVAlignCenter;
string[,] saNames = new string[5, 2];
saNames[0, 0] = "John";
saNames[0, 1] = "Smith";
saNames[1, 0] = "Tom";
saNames[1, 1] = "Brown";
saNames[2, 0] = "Sue";
saNames[2, 1] = "Thomas";
saNames[3, 0] = "Jane";
saNames[3, 1] = "Jones";
saNames[4, 0] = "Adam";
saNames[4, 1] = "Johnson";
oSheet.get_Range("A2", "B6").Value2 = saNames;
oRng = oSheet.get_Range("C2", "C6");
oRng.Formula = "=A2 & \" \" & B2";
oXL.Visible = true;
oXL.UserControl = true;
}
catch (Exception theException)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, theException.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, theException.Source);
MessageBox.Show(errorMessage, "Error");
}
}
The things i write don't really matter but i can't load my own sheet. I tought by replacing
oXL = new Excel.Application();
by
oXL = new Excel.Application("Exemple.xlsx");
I could load my sheet ( call Exemple.xlsx)
Unfortunately it don't work, could you tell me what's wrong?
Thanks!
Once you have your reference to Excel, you must call the Workbooks.Open method to open an existing file:
oXL = new Excel.Application();
oWB = (Excel._Workbook)(oXL.Workbooks.Open("Example.xlsx"));
Related
Hi i try to get better with the c# excel stuff. Right now i try to select some values from an existing excelsheet. For Example: From B4 to C16. So i can replace the values with something else but i dont get it to work.
This is my little method:
public void writeExcelFile()
{
string path = #"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";
oXL = new Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Get all the sheets in the workbook
mWorkSheets = mWorkBook.Worksheets;
//Get the allready exists sheet
mWSheet1 = (Excel.Worksheet)mWorkSheets.get_Item(1);
//Excel.Range range = mWSheet1.UsedRange;
//int colCount = range.Columns.Count;
//int rowCount = range.Rows.Count;
int countRows = mWSheet1.UsedRange.Rows.Count;
int countColumns = mWSheet1.UsedRange.Columns.Count;
object[,] data = mWSheet1.Range[mWSheet1.Cells[1, 1], mWSheet1.Cells[countRows, countColumns]].Cells.Value2;
for (int index = 1; index < 15; index++)
{
mWSheet1.Cells[countRows + index, 1] = countRows + index;
mWSheet1.Cells[countRows + index, 2] = "test" + index;
}
//Excel.Worksheet sheet = workbook.ActiveSheet;
//Excel.Range rng = (Excel.Range)sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[3, 3]);
mWorkBook.SaveAs(path, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled,Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlExclusive,Missing.Value, Missing.Value, Missing.Value,Missing.Value, Missing.Value);
mWorkBook.Close(Missing.Value, Missing.Value, Missing.Value);
mWSheet1 = null;
mWorkBook = null;
oXL.Quit();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
I tried it with get_range but i get an exception that this is not aviable.
It has something to do with the Microsoft.Office.Interop libary 14. Then i tried it with object[,] but the only thing i got to work is that after all used cells to insert test but not to select anything. So any help would be great.
Thanks for your Time and sorry for my english.
EDIT: At least the read process works now and i loop trough a selected range.
Here is the working code:
public void writeExcelFile()
{
String inputFile = #"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";
Excel.Application oXL = new Excel.Application();
#if DEBUG
oXL.Visible = true;
oXL.DisplayAlerts = true;
#else
oXL.Visible = false;
oXL.DisplayAlerts = false;
#endif
//Open the Excel File
Excel.Workbook oWB = oXL.Workbooks.Open(inputFile);
String SheetName = "Gesamt";
Excel._Worksheet oSheet = oWB.Sheets[SheetName];
String start_range = "B4";
String end_range = "R81";
Object[,] values = oSheet.get_Range(start_range, end_range).Value2;
int t = values.GetLength(0);
for (int i = 1; i <= values.GetLength(0); i++)
{
String val = values[i, 1].ToString();
}
oXL.Quit();
}
After many tries i finnaly got a working solution where i can select any cells i want. Maby there are better ways but for me it works as expected.
the code:
public void writeExcelFile()
{
try
{
String inputFile = #"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";
Excel.Application oXL = new Excel.Application();
#if DEBUG
oXL.Visible = true;
oXL.DisplayAlerts = true;
#else
oXL.Visible = false;
oXL.DisplayAlerts = false;
#endif
//Open a Excel File
Excel.Workbook oWB = oXL.Workbooks.Add(inputFile);
Excel._Worksheet oSheet = oWB.ActiveSheet;
List<String> Name = new List<String>();
List<Double> Percentage = new List<Double>();
Name.Add("Anil");
Name.Add("Vikas");
Name.Add("Ashwini");
Name.Add("Tobias");
Name.Add("Stuti");
Name.Add("Raghavendra");
Name.Add("Chithra");
Name.Add("Glen");
Name.Add("Darren");
Name.Add("Michael");
Percentage.Add(78.5);
Percentage.Add(65.3);
Percentage.Add(56);
Percentage.Add(56);
Percentage.Add(97);
Percentage.Add(89);
Percentage.Add(85);
Percentage.Add(76);
Percentage.Add(78);
Percentage.Add(89);
oSheet.Cells[1, 1] = "Name";
oSheet.Cells[1, 2] = "Percentage(%)"; // Here 1 is the rowIndex and 2 is the columnIndex.
//Enter the Header data in Column A
int i = 0;
for (i = 0; i < Name.Count; i++)
{
oSheet.Cells[i + 2, 1] = Name[i];
}
//Enter the Percentage data in Column B
for (i = 0; i < Percentage.Count; i++)
{
oSheet.Cells[i + 2, 2] = Percentage[i];
}
oSheet.Cells[Name.Count + 3, 1] = "AVERAGE";
//Obtain the Average of the Percentage Data
string currentFormula = "=AVERAGE(B2:" + "B" + Convert.ToString(Percentage.Count + 1) + ")";
oSheet.Cells[Percentage.Count + 3, 2].Formula = currentFormula;
//Format the Header row to make it Bold and blue
oSheet.get_Range("A1", "B1").Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.AliceBlue);
oSheet.get_Range("A1", "B1").Font.Bold = true;
//Set the column widthe of Column A and Column B to 20
oSheet.get_Range("A1", "B12").ColumnWidth = 20;
//String ReportFile = #"D:\Excel\Output.xls";
oWB.SaveAs(inputFile, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled,
Type.Missing, Type.Missing,
false,
false,
Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing);
oXL.Quit();
Marshal.ReleaseComObject(oSheet);
Marshal.ReleaseComObject(oWB);
Marshal.ReleaseComObject(oXL);
oSheet = null;
oWB = null;
oXL = null;
GC.GetTotalMemory(false);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.GetTotalMemory(true);
}
catch (Exception ex)
{
String errorMessage = "Error reading the Excel file : " + ex.Message;
MessageBox.Show(errorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
This is not my own code its from a blog: the blog where i got it just edited so it works for me.
I created a WinForm that adds data from textboxs to a List and then when the form closes, exports that data to an excel spreadsheet. I'm in the process of trying to convert my WinForm to a WPF, and the code is no longer working. I'm not getting any errors, it just isn't creating the spreadsheet. Am I missing something here?
protected void OnFormClosing(object sender, EventArgs e)
{
if(signees.Count > 0)
{
initExcelSheet();
}
}
public void initExcelSheet()
{
EXL.Application oXL;
EXL._Workbook oWB;
EXL._Worksheet oWS;
EXL.Range oRng;
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
//Get a new workbook.
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
oWS = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
oWS.Cells[1, 1] = "First Name";
oWS.Cells[1, 2] = "Last Name";
oWS.Cells[1, 3] = "Email";
oWS.Cells[1, 4] = "Expected Graduation Date";
oWS.Cells[1, 5] = "School";
oWS.Cells[1, 6] = "Major";
oWS.Cells[1, 7] = "Favorite Languages";
oWS.get_Range("A1", "G1").Font.Bold = true;
oWS.get_Range("A1", "G1").VerticalAlignment =
Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
int count = 2;
foreach(Person x in signees)
{
oWS.Cells[count, 1] = x.firstName;
oWS.Cells[count, 2] = x.lastName;
oWS.Cells[count, 3] = x.email;
oWS.Cells[count, 4] = x.gradDate.ToString("yyyy-MM-dd");
oWS.Cells[count, 5] = x.schoolName;
oWS.Cells[count, 6] = x.fos;
oWS.Cells[count, 7] = x.fcl;
count += 1;
}
oRng = oWS.get_Range("A1", "G1");
oRng.EntireColumn.AutoFit();
try
{
oWB.SaveAs(fileName(school, DateTime.Now));
}
catch(Exception e)
{
Console.Write(e.ToString());
}
oWB.Close();
I am trying to generate line chart from datatable but output is not coming fine. i guess there is axis related problem is there. so it will be great help if some one rectify my code.
private void button1_Click(object sender, EventArgs e)
{
System.Data.DataTable dt = GetGraphData();
Excel.Application xla = new Excel.Application();
xla.Visible = true;
Excel.Workbook wb = xla.Workbooks.Add(Excel.XlSheetType.xlWorksheet);
Excel.Worksheet ws = (Excel.Worksheet)wb.ActiveSheet;
//********************** Now create the chart. *****************************
Excel.ChartObjects chartObjs = (Excel.ChartObjects)ws.ChartObjects(Type.Missing);
Excel.ChartObject chartObj = chartObjs.Add(250, 60, 300, 300);
Excel.Chart xlChart = chartObj.Chart;
int nRows = 2;
int nColumns = dt.Rows.Count;
string upperLeftCell = "B2";
int endRowNumber = System.Int32.Parse(upperLeftCell.Substring(1))
+ nRows - 1;
char endColumnLetter = System.Convert.ToChar(
Convert.ToInt32(upperLeftCell[0]) + nColumns - 1);
string upperRightCell = System.String.Format("{0}{1}",
endColumnLetter, System.Int32.Parse(upperLeftCell.Substring(1)));
string lowerRightCell = System.String.Format("{0}{1}",
endColumnLetter, endRowNumber);
Excel.Range rg = ws.get_Range(upperLeftCell, lowerRightCell);
for (int i = 1; i <= dt.Rows.Count; i++)
{
rg[1, i] = dt.Rows[i - 1][0].ToString(); //For Adding Header Text
rg[2, i] = int.Parse(dt.Rows[i - 1][1].ToString()); //For Adding Datarow Value
}
Excel.Range chartRange = ws.get_Range(upperLeftCell, lowerRightCell);
xlChart.SetSourceData(chartRange, Type.Missing);
xlChart.ChartType = Excel.XlChartType.xlLine;
// *******************Customize axes: ***********************
Excel.Axis xAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlCategory,
Excel.XlAxisGroup.xlPrimary);
//xAxis.HasTitle = true;
// xAxis.AxisTitle.Text = "X Axis";
//Excel.Axis yAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlSeriesAxis,
// Excel.XlAxisGroup.xlPrimary);
//3d chart
//yAxis.HasTitle = true;
//yAxis.AxisTitle.Text = "Y Axis";
Excel.Axis zAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlValue,
Excel.XlAxisGroup.xlPrimary);
//zAxis.HasTitle = true;
//zAxis.AxisTitle.Text = "Z Axis";
// *********************Add title: *******************************
xlChart.HasTitle = true;
xlChart.ChartTitle.Text = "Project Status Graph";
// *****************Set legend:***************************
xlChart.HasLegend = true;
//FileStream file = new FileStream(#"d:\pop.xls", FileMode.Create);
//file.Close();
wb.SaveCopyAs(#"d:\pop.xls");
// ****************For Quiting The Excel Aplication ***********************
if (xla != null)
{
xla.DisplayAlerts = false;
wb.Close();
wb = null;
xla.Quit();
xla = null;
}
}
private System.Data.DataTable GetGraphData()
{
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("ProjectStatus"), new DataColumn("per") });
DataRow dr1 = dt.NewRow();
dr1[0] = "Compleet";
dr1[1] = 20;
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2[0] = "Pending";
dr2[1] = 20;
dt.Rows.Add(dr2);
DataRow dr3 = dt.NewRow();
dr3[0] = "UnCompleet";
dr3[1] = 20;
dt.Rows.Add(dr3);
return dt;
}
i guess these below line are not fine.
Excel.Axis xAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlCategory,
Excel.XlAxisGroup.xlPrimary);
//xAxis.HasTitle = true;
// xAxis.AxisTitle.Text = "X Axis";
//Excel.Axis yAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlSeriesAxis,
// Excel.XlAxisGroup.xlPrimary);
//3d chart
//yAxis.HasTitle = true;
//yAxis.AxisTitle.Text = "Y Axis";
Excel.Axis zAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlValue,
Excel.XlAxisGroup.xlPrimary);
//zAxis.HasTitle = true;
//zAxis.AxisTitle.Text = "Z Axis";
this way i solved
this is just a sample code not real life implementation
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel;
using System.IO;
namespace WindowsForms_chartexcel
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//add data
xlWorkSheet.Cells[1, 1] = "";
xlWorkSheet.Cells[1, 2] = "Student1";
xlWorkSheet.Cells[1, 3] = "Student2";
xlWorkSheet.Cells[1, 4] = "Student3";
xlWorkSheet.Cells[2, 1] = "Term1";
xlWorkSheet.Cells[2, 2] = "80";
xlWorkSheet.Cells[2, 3] = "65";
xlWorkSheet.Cells[2, 4] = "45";
xlWorkSheet.Cells[3, 1] = "Term2";
xlWorkSheet.Cells[3, 2] = "78";
xlWorkSheet.Cells[3, 3] = "72";
xlWorkSheet.Cells[3, 4] = "60";
xlWorkSheet.Cells[4, 1] = "Term3";
xlWorkSheet.Cells[4, 2] = "82";
xlWorkSheet.Cells[4, 3] = "80";
xlWorkSheet.Cells[4, 4] = "65";
xlWorkSheet.Cells[5, 1] = "Term4";
xlWorkSheet.Cells[5, 2] = "75";
xlWorkSheet.Cells[5, 3] = "82";
xlWorkSheet.Cells[5, 4] = "68";
Excel.Range chartRange ;
Excel.ChartObjects xlCharts = (Excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);
Excel.ChartObject myChart = (Excel.ChartObject)xlCharts.Add(200, 80, 300, 250);
Excel.Chart chartPage = myChart.Chart;
chartRange = xlWorkSheet.get_Range("A1", "d5");
chartPage.SetSourceData(chartRange, misValue);
//chartPage.ChartType = Excel.XlChartType.xlColumnClustered;
chartPage.ChartType = Excel.XlChartType.xlLine;
if (File.Exists(#"d:\test.xls"))
{
File.Delete(#"d:\test.xls");
}
xlWorkBook.SaveAs(#"d:\test.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel file created , you can find the file d:\test.xls");
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}
I need to create an Excel spreadsheet and then I need to rename the sheets. What am I doing wrong?
Here is the code I have so far:
using System;
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
public class CreateExcelWorksheet
{
static void Main()
{
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
oXL = new Excel.Application();
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
oSheet.Cells[1, 1] = "First Name";
oSheet.Cells[1, 2] = "Last Name";
oSheet.Cells[1, 3] = "Full Name";
oSheet.Cells[1, 4] = "Salary";
//Format A1:D1 as bold, vertical alignment = center.
oSheet.get_Range("A1", "D1").Font.Bold = true;
oSheet.get_Range("A1", "D1").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;
oSheet.Name = "NewOne";
string filename = "C:\\" + DateTime.Now.ToString("dd_MM_yy_hhmmss");
oWB.SaveAs(filename + "asdaa" + ".xlsx");
oWB.Close();
}
}
oWB.Worksheets is where you find the sheets.
Can take them by index Worksheets[1] (or 2, or 3...)
Can take them by name Worksheets["SheetName"]
They come as object, so cast them to (Worksheet).
Worksheet oSheet = (Worksheet)oWB.Worksheets["TheSheetYouWant"];
To change name: oSheet.Name = "NewName";
Even shorter:
workbook.Worksheets[1].Name = "Sheet Name";
I am creating an excel report using data coming from mssql server in my asp.net application. Here is my method:
[WebMethod]
public static string ExportToExcel(string sourcetype)
{
Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
try
{
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = false;
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
List<ExcelReport> dataToExport = APIClient.GetExcelReportData(Utility.getCurrentFilterId(), sourcetype);
oSheet.Cells[1, 1] = "Source";
oSheet.Cells[1, 2] = "UserName";
oSheet.Cells[1, 3] = "Name";
oSheet.Cells[1, 4] = "Message";
oSheet.Cells[1, 5] = "Title";
//oSheet.Cells[1, 6] = "Date";
int activeRow = 2;
for (int i = 0; i < dataToExport.Count; i++)
{
oSheet.Cells[activeRow, 1] = dataToExport[i].Source;
oSheet.Cells[activeRow, 2] = dataToExport[i].UserName;
oSheet.Cells[activeRow, 3] = dataToExport[i].Name;
oSheet.Cells[activeRow, 4] = dataToExport[i].Message;
oSheet.Cells[activeRow, 5] = dataToExport[i].MessageTitle;
//oSheet.Cells[activeRow, 6] = dataToExport[i].EntityDate;
activeRow++;
}
oSheet.get_Range("A1", "Z1").Font.Bold = true;
oSheet.get_Range("A1", "Z1").VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
oRng = oSheet.get_Range("A1", "Z1");
oRng.EntireColumn.AutoFit();
oXL.Visible = false;
oXL.UserControl = false;
string strFile = "report" + System.DateTime.Now.Ticks.ToString() + ".xls";
string strCurrentDir = HttpContext.Current.Server.MapPath(".") + "\\ExcelReports\\";
oWB.SaveAs(strCurrentDir + strFile, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, null, null, false,
false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, false, false, null, null, null);
//oWB.SaveCopyAs(strCurrentDir + strFile);
oWB.Close(null, null, null);
oXL.Workbooks.Close();
oXL.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(oRng);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oXL);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oWB);
oSheet = null;
oWB = null;
oXL = null;
GC.Collect(); // force final cleanup!
//errLabel.Text = "Download Report";
//string result = "Raporu İndir";
string result = "ExcelReports/" + strFile;
return result;
}
catch (Exception theException)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, theException.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, theException.Source);
return errorMessage;
}
}
It works fine in my machine and at the server that application published to when I opened the source code in vs 2010 and press F5. But if I try to access my application using the browser through IIS, I'm getting HRESULT: 0x800A03EC error.
I tried the following command:
appcmd set config -section:asp -enableParentPaths:true
I tried to give write permissions to my folder.
I tried to change my MS Excel application settings from Component Services.
But no way! I could not get it working. Do you have any idea? Am I doing a mistake in configuration?
Thanks in advance,
I reproduced your issue.. tried all: oWB.SaveAs / oWB._SaveAs / ( oXL.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet ).SaveAs / oWB.Application.ActiveWorkbook.SaveAs all throw exception: HRESULT: 0x800A03EC...
But I see you tried with: oWB.SaveCopyAs(strCurrentDir + strFile);
and it works if I set next:
oWB.Saved = true;
oWB.SaveCopyAs( strCurrentDir + strFile );
Why you don't use SaveCopyAs ?
Make a "Desktop" folder like below
C:\Windows\SysWOW64\config\systemprofile\Desktop
C:\Windows\System32\config\systemprofile\Desktop
If the call to Excel interop is happening on the same thread as ASP.NET -- i.e., in response to your UI -- then the Excel needs some sort of userprofile to work. IIS doesn't provide this by default, but as long as some folders exist with the correct permissions then it can work.
C:\Windows\SysWOW64\config\systemprofile\Desktop (for 64-bit Servers only)
C:\Windows\System32\config\systemprofile\Desktop (for both 32-bit and 64-bit Servers)
From the final section of https://www.ryadel.com/en/office-interop-dcom-config-windows-server-iis-word-excel-access-asp-net-c-sharp/#0x800A03EC_Cannot_access_the_file