4

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 = "<A href=http://" + strMachineName + "/ExcelGen/" + strFile + ">Download Report</a>";
        //string result = "<a href=\"~/ExcelReports/" + strFile + ">Raporu İndir</a>";
        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,

xkcd
  • 2,538
  • 11
  • 59
  • 96
  • 3
    I think you should pass System.Missing.Value instead of null values when calling interop – Robert Mar 16 '11 at 15:25
  • Since you haven't mentioned it 0x800A03EC == ERROR_INVALID_FLAGS. But you shouldn't be automating Excel from IIS - it's [not officially supported](http://stackoverflow.com/questions/151005/create-excel-xls-and-xlsx-file-from-c/151014#151014) since Excel assumes it has an interactive desktop. There's [plenty of XLS/XLSX generation libraries](http://stackoverflow.com/questions/151005/create-excel-xls-and-xlsx-file-from-c) you can use instead. – Rup Mar 16 '11 at 18:39

3 Answers3

14

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 ?

mastak
  • 1,397
  • 1
  • 14
  • 28
  • 1
    Thanks for your answer. It works well with this detailed configuration. http://stackoverflow.com/questions/1981395/windows-7-net-excel-saveas-error-exception-from-hresult-0x800a03ec/1986575#1986575 – xkcd Mar 16 '11 at 18:42
  • Excellent. Excellent. Workaround is always delicious ;) +1. – Saeed Neamati May 13 '12 at 06:44
  • I had Windows 2008, Office 2003, a windows service, running under a domain user, that failed at SaveAs line. Tried SaveCopyAs (without .Saved = true though) and had a similar error. It suddenly started to work afterI gave Everyone permissions on C:\Users\[User] folder (I know this is not good, so I think I should have give access to this user to Local and Roaming folders only). – Alex May 08 '15 at 12:12
1

Make a "Desktop" folder like below

C:\Windows\SysWOW64\config\systemprofile\Desktop
C:\Windows\System32\config\systemprofile\Desktop
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
Siri How
  • 113
  • 3
  • 10
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient [reputation](http://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](http://stackoverflow.com/help/privileges/comment). - [From Review](/review/low-quality-posts/10293956) – Muhammed Refaat Nov 22 '15 at 12:59
  • @MuhammedRefaat This may be a valid answer. If you think this is wrong or not useful then you can downvote it. – Artjom B. Nov 22 '15 at 14:52
  • @ArtjomB. it came to me through reviewing low quality posts, and I estimated it as a commentary because of two points, first I think it's a try or a shot for a fast fix to the problem and not a fulfill answer, and such fix in SO usually comes as a comment, second I believe he must make some clarification about how his answer solves the problem of the OP. Thanks for your comment. – Muhammed Refaat Nov 22 '15 at 17:34
  • @MuhammedRefaat Yes, there is a lot of information missing, but that doesn't make it [*Not An Answer*](http://meta.stackexchange.com/q/225370/266187). It may be just a bad answer, but you never know which curiosities solve a Macrohard problem. – Artjom B. Nov 22 '15 at 18:10
  • @ArtjomB. I just did my best in estimating this answer level, may be you are more experience than me in such posts, anyway thanks for your hint – Muhammed Refaat Nov 23 '15 at 07:55
  • 你地食屎啦咁都話吾係answer作本書比你好無呀你老母 – Siri How Nov 23 '15 at 13:53
  • @Muhammed Refaat You CONFIRMED it's nothing help? How could you proof this wont work? It's not the unique solution but it must be one of the way to solve the problem. AT LEAST I TRIED and WORK even though I hvn't provide enough explaination but it could open the door of the question if you just following the step. And, lots of another forums have the same answer. – Siri How Nov 24 '15 at 03:08
  • @SiriHow Here in SO, it's not about if the answer will work or not, even if it will work, providing an answer without an explanation is invalid here, and provide a link-only answer is invalid here also even if this link is answering the question, that's why your answer is flagged as a low quality answer which made it came to me through me review process to the low quality posts, and also that's why your answer received downvotes although I didn't even downvote it myself. kindly have a look at the following link (http://stackoverflow.com/help/how-to-answer) – Muhammed Refaat Nov 24 '15 at 07:50
  • @Muhammed Refaat The guide just said for a GOOD answer that explaination is better but not a MUST. No explanation could be classified as not GOOD but may still be an answer that could give the asker a direction. In the page you provided said "Any answer that gets the asker going in the right direction is helpful, but do try to mention any limitations, assumptions or simplifications in your answer. Brevity is acceptable, but fuller explanations are better." To be continued... – Siri How Nov 25 '15 at 05:01
  • @Muhammed Refaat You said "This does not provide an answer to the question" at the beginning. The question from the asker is "Do you have any idea?". I gave my idea. As Artjom said "This may be a valid answer. If you think this is wrong or not useful then you can downvote it". If it cant solve your problem, you could say it isn't the answer for you and downvote. But you are not facing the problem and never try what someone recommened and just say it's not an answer. I don't agree with that. The point I wanna express is the different between answer, good answer and not an answer. – Siri How Nov 25 '15 at 05:01
  • well, first of all "This does not provide an answer to the question" is an automated comment generated by SO after I reviewed the answer, I believe it can be a "fix" for the problem but not a complete answer, and after all it's not my opinion only, it's the opinion of another "three" users at least, which mean I didn't came with that by my own, some one and another saw this answer has a problem and they redirected it to be reviewed by someone which is me and another 2-4 reviewers, this is how it going here.. – Muhammed Refaat Nov 25 '15 at 08:04
  • and after all it's our estimations to make the community even better and a more reliable place for you and me, so may be we are right and may be we are wrong, but after all there is nothing in person, and we all here try our hard to use our privileges in a benefited way. – Muhammed Refaat Nov 25 '15 at 08:06
  • I now realized that SO was running under those rules which are not make sense to me and I don't understand why there are ppl agree with such rules and pick bone from egg (Direct answer is not an answer). Of course judging the answer will give improvement so I am fine to be requested to give more explanation or detail. Always marks others "This does not provide an answer to the question" no mater from the system or human will only discourage ppl for giving hands. – Siri How Nov 25 '15 at 10:49
  • I dont know how you came up with that but after 3 days this solved my problem! – E-A Nov 25 '20 at 11:41
0

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

Ron Newcomb
  • 2,886
  • 21
  • 24