创建EXCEL并将其打开

时间:2017-12-08 01:03:08

标签: c# asp.net excel

我正在创建一个excel文件,我必须立即打开它。 显然,当我在localhost上创建它时,我可以获取该文件,但是当我在IIS上发布我的Web应用程序时,这不起作用,因为我认为它是在服务器端创建的......

所以我创建了excel文件,并尝试上传到服务器,然后下载它,但我无法创建它,如果我在localhost上运行它,但是当我发布时不起作用。

有什么建议吗?

这是我的代码:

我将此库用于Excel:

using Microsoft.Office.Core;
using Excelo = Microsoft.Office.Interop.Excel; 
using Microsoft.Office.Interop;
using System.Reflection;
using System.Globalization;

然后,我启动我的excel文件:

private void sacConsulPend_GenRemito()
{   // DB 
    string conn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
    DataSet dsRemito = new DataSet();
    DataTable dtCons = new DataTable();



    using (SqlConnection sqlCon = new SqlConnection(conn))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            try
            {   //SP for data query
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.CommandText = "SACBUS_CONSUL_SOLICITUDEXIST";
                cmd.Parameters.AddWithValue("@ID_CONSULTA", 
                    Convert.ToInt32(lblSac_ConPenDet_idCons.Text.Replace(" ", "")));

                cmd.Connection = sqlCon;
                sqlCon.Open();

                SqlDataAdapter dapC = new SqlDataAdapter(cmd);
                dapC.Fill(dsRemito);


            }
            catch (Exception sqlex)
            {
                throw sqlex;
            }
        }
    }

    Excelo.Application oXL;
    Excelo._Workbook oWB;
    Excelo._Worksheet oSheet;
    Excelo.Range oRng;

    try
    {

        //Start Excel 
        oXL = new Excelo.Application();

        //new blank workbook.
        oWB = (Excelo._Workbook)(oXL.Workbooks.Add(System.Reflection.Missing.Value));
        oSheet = (Excelo._Worksheet)oWB.ActiveSheet;
        object misValue = System.Reflection.Missing.Value;

        //Text Format
        oSheet.get_Range("A1", "Z1000").Font.Name = "Courier New";
        oSheet.get_Range("A1", "Z1000").Font.Size = 7;
        oSheet.get_Range("A1", "Z1000").Font.Bold = true;
        oSheet.get_Range("A1", "Z1000").NumberFormat = "@";

        oSheet.get_Range("D1", "E1").Cells.Merge();
        oSheet.get_Range("A1", "F1").Font.Bold = true;
        oSheet.get_Range("A1", "F1").Font.Italic = true;
        oSheet.get_Range("A1", "F1").VerticalAlignment = Excelo.XlVAlign.xlVAlignCenter;
        oSheet.get_Range("A1", "F1").HorizontalAlignment = Excelo.XlVAlign.xlVAlignCenter;
        oSheet.get_Range("A1", "F1").Font.Size = 9;

        //Logo Lockers
        oSheet.Shapes.AddPicture(Server.MapPath("~/images/LockersLogo.jpg"), MsoTriState.msoFalse, MsoTriState.msoCTrue, 0, 0, 60, 20);


        /* 
        Excel Content
        */


         //Save ExcelFile
        var filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/Files/Envios/"), lblSac_ConPenDet_idCons.Text.Replace(" ", "") + ".xlsx");
        oWB.SaveAs(filePath, Excelo.XlFileFormat.xlOpenXMLWorkbook, Missing.Value,
        Missing.Value, false, false, Excelo.XlSaveAsAccessMode.xlNoChange,
        Excelo.XlSaveConflictResolution.xlUserResolution, true,
        Missing.Value, Missing.Value, Missing.Value);



    }
    catch (Exception thex)
    {
        String errorMessage;
        errorMessage = "Error en la creacion del archivo Excel: ";
        errorMessage = String.Concat(errorMessage, thex.Message);
        errorMessage = String.Concat(errorMessage, " Line: ");
        errorMessage = String.Concat(errorMessage, thex.Source);
    }

}

2 个答案:

答案 0 :(得分:1)

您可以使用适用于您的方案的(官方)OpenXML SDK。它不允许您在服务器环境中实际计算和运行函数,但它有助于创建和操作工作簿。 Download 然而,OpenXML SDK并不是每个人都喜欢的,因为它需要一些学习,有时需要很多代码来实现一些简单的事情。

幸运的是,还有许多其他库允许创建没有Office的XLS / X文件,例如ExcelLibrary或其后续版EEPlusNPOI(请参阅johnleniel),以及许多商业第三方组件。

我可以想象像Crystal Reports这样的专用报表组件(也可以导出到XLS / X)对你来说也很有用。

答案 1 :(得分:0)

现在这是我的代码,使用EEPlus它没有完成,但可以在服务器端创建一个文件,之后我下载相同的创建文件。

using OfficeOpenXml;
using System.IO;
using System.Drawing;
using OfficeOpenXml.Drawing;

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

这是最相关的:

public static string GenerarExcel(DirectoryInfo outputDir)
{
    string conn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
    DataSet dsRemito = new DataSet();
    DataTable dtCons = new DataTable();


    using (SqlConnection sqlCon = new SqlConnection(conn))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            try
            {//SP for sql query
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.CommandText = "SACBUS_CONSUL_SOLICITUDEXIST";
                cmd.Parameters.AddWithValue("@ID_CONSULTA", 66);
                //66 wil be a variable, this is only for my tests

                cmd.Connection = sqlCon;
                sqlCon.Open();

                SqlDataAdapter dapC = new SqlDataAdapter(cmd);
                dapC.Fill(dsRemito);


            }
            catch (Exception sqlex)
            {
                throw sqlex;
            }
        }
    }


    FileInfo newFile = new FileInfo(outputDir.FullName + @"\Sample1.xlsx");

    if (newFile.Exists)
    {
        newFile.Delete();
        newFile = new FileInfo(outputDir.FullName + @"\Sample1.xlsx"); //preparar nombre archivo
    }

    using (ExcelPackage package = new ExcelPackage(newFile))
    {
        // Agregar hoja a worbook
        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Envios");

        // Header
        worksheet.Cells[1, 3].Value = "SISTEMA DE GESTIÓN DE CALIDAD ISO 9001:2008";
        worksheet.Cells[2, 3].Value = "PEDIDO DE CONSULTA A BODEGA";
        worksheet.Cells[1, 5].Value = "Código:";
        worksheet.Cells[1, 6].Value = "FOR-PCV-COM-SAC-PEBOD-02  ";
        worksheet.Cells[2, 5, 2, 6].Merge = true;

        // Estilo del Encabezado
        using (var range = worksheet.Cells[1, 1, 1, 5]) // De la celda 1,1 a la 1,5
        {
            range.Style.Font.Bold = true; // Negrita
            range.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid; // Solido lleno
            range.Style.Fill.BackgroundColor.SetColor(Color.DarkBlue); //Background
            range.Style.Font.Color.SetColor(Color.White);// Font color
        }


        // Pie de Pagina
        // lineas en la cuadricula
        worksheet.Cells["A5:E5"].Style.Border.Top.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
        worksheet.Cells["A5:E5"].Style.Font.Bold = true; // estilo del pie de pagina



        //Formatos
        //Formato Numerico
        worksheet.Cells["C2:C5"].Style.Numberformat.Format = "#,##0";   // Formato Entero
        worksheet.Cells["D2:E5"].Style.Numberformat.Format = "#,##0.00";    // Formato Decimal


               worksheet.Cells["A2:A4"].Style.Numberformat.Format = "@"; //Formato texto
        worksheet.Cells.AutoFitColumns(0); //AutoAjustar celdas


        // Numero de pagina + total de paginas a la derecha del pie de pagina
        worksheet.HeaderFooter.OddFooter.RightAlignedText = string.Format("Pagina {0} of {1}", ExcelHeaderFooter.PageNumber, ExcelHeaderFooter.NumberOfPages);

        // Nombre de la hoja al centro del pie de pagina
        worksheet.HeaderFooter.OddFooter.CenteredText = ExcelHeaderFooter.SheetName;

        // Ruta a la izquierda del pie de pagina
        worksheet.HeaderFooter.OddFooter.LeftAlignedText = ExcelHeaderFooter.FilePath + ExcelHeaderFooter.FileName;


        //System.Drawing.Image img = System.Drawing.Image.FromFile(@"C:\temporal\asp\ExcelLibrary\LockersLogo.jpg");
        System.Drawing.Image img = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("~/image/LockersLogo.jpg"));

        ExcelPicture pic = worksheet.Drawings.AddPicture("Sample", img);
        pic.SetPosition(0, 0, 6, 0);
        pic.SetSize(150, 75);



        //Items consultados
        var registros = 0;
        for (int i = 0; i < dsRemito.Tables[0].Rows.Count; i++)
        {
            worksheet.Cells[8 + i, 1].Value = dsRemito.Tables[0].Rows[i]["CAJA_CODIGO"];
            worksheet.Cells[8 + i, 2].Value = dsRemito.Tables[0].Rows[i]["CAJA_NUMERO"];
            worksheet.Cells[8 + i, 3].Value = dsRemito.Tables[0].Rows[i]["CAJA_CONTENIDO_NUMERO"];
            worksheet.Cells[8 + i, 4].Value = dsRemito.Tables[0].Rows[i]["ITEM"];



            registros = i;
        }




        package.Save(); //guardar workbook

    }

    return newFile.FullName;
}


protected void DownloadFile()
{

    string rutaUsr = "~/" + "Files/";
    string filePath = rutaUsr + "Sample1" + ".xlsx";
    Response.ContentType = ContentType;
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
    Response.WriteFile(filePath);
    Response.End();

}

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        //DirectoryInfo outputDir = new DirectoryInfo(@"C:\temporal\asp\ExcelLibrary");
        DirectoryInfo outputDir = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/Files/"));
        GenerarExcel(outputDir);

        DownloadFile();
    }

    catch (Exception ex)
    {
        Console.WriteLine("Error: {0}", ex.Message);
    }

}
相关问题