【问题标题】:How to create Excel file in asp.net如何在asp.net中创建Excel文件
【发布时间】:2015-02-10 09:29:21
【问题描述】:

我想在 asp.net 中创建 Excel 工作表。我已经为此编写了代码,并且在本地系统中运行良好,但是当我在服务器上对其进行测试时,它会出现以下错误。

检索 CLSID 为 {00024500-0000-0000-C000-000000000046} 的组件的 COM 类工厂失败,原因是以下错误:80070005。

我的代码是。

private static System.Data.DataTable GetDataSet()
    {
        System.Data.DataTable dt = new System.Data.DataTable("Table");
        dt.Columns.Add("Name", Type.GetType("System.String"));
        dt.Columns.Add("Address", Type.GetType("System.String"));
        dt.Columns.Add("Phone", Type.GetType("System.String"));

        DataRow dr = dt.NewRow();
        dr["Name"] = "Balaji Selvarajan";
        dr["Address"] = "Reddiyur";
        dr["Phone"] = "000-000-0000";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["Name"] = "Balaji S";
        dr["Address"] = "Kattumannar Koil";
        dr["Phone"] = "000-000-0000";
        dt.Rows.Add(dr);
        return dt;
    }


    private static void DataSetToExcel(System.Data.DataTable dt, Boolean generateIdentity)
    {
        try
        {
            string Filename = HttpContext.Current.Server.MapPath("~/Doc/") + "Test.xls";
            string imagepath1 = HttpContext.Current.Server.MapPath("~/Doc/") + "Test.xls";
            FileInfo fi = new FileInfo(HttpContext.Current.Server.MapPath("~/Doc/") + "Test.xls");
            if (fi.Exists)
            {
                fi.Delete();
            }
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            xlApp.Visible = false;
            Microsoft.Office.Interop.Excel.Workbook wb = xlApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            object misValue = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets.Add(misValue, misValue, misValue, misValue);
            ws.Name = "Test";

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (i == 0)
                        ws.Cells[1, j + 1] = dt.Columns[j].ColumnName;
                    ws.Cells[i + 2, j + 1] = dt.Rows[i][j].ToString();
                }
                ws.Protect("1235", true, true, true, true, true, true, true, true, true, true, true, true, true, true, true);
            }
            wb.Protect("my", true, true);
            wb.Password = "1235";
            wb.SaveAs(Filename, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, "1235", misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            wb.Close(true, misValue, misValue);
            xlApp.Visible = true;
            xlApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
            HttpContext.Current.Response.ContentType = "Application/Excel";
            string FilePath = imagepath1;
            HttpContext.Current.Response.WriteFile(FilePath);
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=Test.xls");
            HttpContext.Current.Response.End();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void BtnDn_Click(object sender, EventArgs e)
    {
        DataSetToExcel(GetDataSet(), false);
    }

我无法解决这个问题,请帮助我。请尽快给我解决方案。

我正在使用 Asp.net C#。

【问题讨论】:

  • 在服务器上使用 Office(如来自 asp.net)是 not supported。有几个组件(也是免费软件)可以让您从 asp.net 生成 Excel 文件。
  • 你能给我这些免费软件组件的 url 以生成 excel 文件吗
  • 完全同意@HansKesting - 但也要确保如果您正在使用不受支持和错误的方法,COM 库已在服务器上注册。

标签: c# asp.net excel


【解决方案1】:

试试这个

     using System;  
     using System.Collections.Generic;   
     using System.Data;  
     using System.Linq;  
     using System.Text;  
     using System.Threading.Tasks; 
     using Office = Microsoft.Office.Core;  
     using Excel = Microsoft.Office.Interop.Excel;

     namespace Excel   
     {   
         public class ExcelUtlity   
          {                      

    public bool WriteDataTableToExcel(System.Data.DataTable dataTable, string worksheetName, string saveAsLocation, string ReporType)        {
     Microsoft.Office.Interop.Excel.Application excel;
Microsoft.Office.Interop.Excel.Workbook excelworkBook;
Microsoft.Office.Interop.Excel.Worksheet excelSheet;
Microsoft.Office.Interop.Excel.Range excelCellrange;
try
{
    // Start Excel and get Application object.
   excel = new Microsoft.Office.Interop.Excel.Application();
    // for making Excel visible
    excel.Visible = false;
    excel.DisplayAlerts = false;
    // Creation a new Workbook
    excelworkBook = excel.Workbooks.Add(Type.Missing);
    // Workk sheet             
    excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelworkBook.ActiveSheet;
    excelSheet.Name = worksheetName;
    excelSheet.Cells[1, 1] = ReporType;
    excelSheet.Cells[1, 2] = "Date : " + DateTime.Now.ToShortDateString();               
    // loop through each row and add values to our sheet
    int rowcount = 2;
    foreach (DataRow datarow in dataTable.Rows)
    {
        rowcount += 1;
        for (int i = 1; i <= dataTable.Columns.Count; i++)
        {
            // on the first iteration we add the column headers
            if (rowcount == 3)
            {
                excelSheet.Cells[2, i] = dataTable.Columns[i-1].ColumnName;
                excelSheet.Cells.Font.Color = System.Drawing.Color.Black;
            }
            excelSheet.Cells[rowcount, i] = datarow[i-1].ToString();
            //for alternate rows
            if (rowcount > 3)
            {
                if (i == dataTable.Columns.Count)
                {
                    if (rowcount % 2 == 0)
                    {
                        excelCellrange = excelSheet.Range[excelSheet.Cells[rowcount, 1], excelSheet.Cells[rowcount, dataTable.Columns.Count]];
                        FormattingExcelCells(excelCellrange, "#CCCCFF", System.Drawing.Color.Black,false);
                    }
                }
            }
        }
    }
    // now we resize the columns
    excelCellrange = excelSheet.Range[excelSheet.Cells[1, 1], excelSheet.Cells[rowcount, dataTable.Columns.Count]];
    excelCellrange.EntireColumn.AutoFit();
    Microsoft.Office.Interop.Excel.Borders border = excelCellrange.Borders;
    border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
    border.Weight = 2d;
    excelCellrange = excelSheet.Range[excelSheet.Cells[1, 1], excelSheet.Cells[2, dataTable.Columns.Count]];
    FormattingExcelCells(excelCellrange, "#000099", System.Drawing.Color.White, true);
    //now save the workbook and exit Excel
    excelworkBook.SaveAs(saveAsLocation);;
    excelworkBook.Close();
    excel.Quit();
    return true;
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
    return false;
}
finally
{
    excelSheet = null;
    excelCellrange = null;
    excelworkBook = null;
}
 }       
    /// FUNCTION FOR FORMATTING EXCEL CELLS

public void FormattingExcelCells(Microsoft.Office.Interop.Excel.Range range, string HTMLcolorCode, System.Drawing.Color fontColor, bool IsFontbool)
  {
      range.Interior.Color=System.Drawing.ColorTranslator.FromHtml(HTMLcolorCode);
range.Font.Color = System.Drawing.ColorTranslator.ToOle(fontColor);
if (IsFontbool == true)
{
    range.Font.Bold = IsFontbool;
}
   }

  }

【讨论】:

  • 有点奇怪,在 ASP.Net Web 应用程序中看到using System.Windows.Forms
  • 以上代码是针对windows应用的。我需要网络应用程序。
  • 我尝试将上述代码实现到 Web 应用程序,但在“Range”关键字中显示错误。
  • 在你的项目Microsoft.Vbe.Interop.dll,Microsoft.Office.Interop.Excel.xml,Microsoft.Office.Interop.Excel.dll,office.dll中添加以下dll
【解决方案2】:

错误 80070005 是拒绝访问错误。尝试将您的 AppPool 配置为在 LocalSystem(而不是 ApplicationPoolIdentity)下运行,或者尝试在组件服务中授予 Excel 权限:

  1. 从“开始”菜单中,单击“运行”并键入 Dcomcnfg.exe。
  2. 在组件服务中,单击控制台根目录,展开组件服务,展开计算机,展开我的电脑,展开 DCOMConfig。
  3. 搜索 Microsoft Word 14.0 对象库。点击它。
  4. 右键单击并选择属性。
  5. 在安全选项卡上,选择“启动和激活”部分中的自定义。
  6. 单击编辑并添加运行应用程序的应用程序池的标识。
  7. 对“访问权限”重复上述步骤

AppPool 账号解决方案来自这里:"Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

组件服务权限答案来自这里:Retrieving the COM class factory for component with CLSID failed due to the following error: 80070005 Access is denied

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    • 2013-07-31
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多