Foros del Web » Programación para mayores de 30 ;) » .NET »

c# Convertir EXCEL a PDF

Estas en el tema de c# Convertir EXCEL a PDF en el foro de .NET en Foros del Web. Hola a todos, he creado un servicio que convierte archivos excel a PDF. La función que me los imprime es la siguiente: Código: /// <summary> ...
  #1 (permalink)  
Antiguo 13/05/2010, 03:32
 
Fecha de Ingreso: diciembre-2007
Ubicación: España
Mensajes: 51
Antigüedad: 16 años, 4 meses
Puntos: 1
c# Convertir EXCEL a PDF

Hola a todos,

he creado un servicio que convierte archivos excel a PDF. La función que me los imprime es la siguiente:

Código:
/// <summary>
        /// Genera un .PDF con la página actual del archivo .xls
        /// </summary>
        /// <param name="sFicheroXLS">Ruta al archivo .xls</param>
        /// <param name="sDirectorio">Directorio del fichero de salida</param>
        /// <param name="sFicheroPDF">Nombre del fichero SIN EXTENSIÓN NI PUNTOS</param>
        private bool PrintIt(String sFicheroXLS, String sDirectorio, String sFicheroPDF)
		{
            try
            {
                bool bResultado = true;
                string DefaultPrinter;
                FileInfo fi;
                PDFCreator.clsPDFCreatorOptions opt;
                fi = new FileInfo(sFicheroXLS);
                if (fi.Name.Length > 0)
                {
                    CLogger.MsgDebug("Comprobando archivo a imprimir");
                    if (!_PDFCreator.cIsPrintable(fi.FullName))
                    {
                        CLogger.MsgDebug("File '" + fi.FullName + "' is not printable!");
                        return false;
                    }


                    opt = _PDFCreator.cOptions;
                    opt.UseAutosave = 1;
                    opt.UseAutosaveDirectory = 1;
                    opt.AutosaveDirectory = sDirectorio;
                    opt.AutosaveFormat = 0;
                    opt.AutosaveFilename = sFicheroPDF;
                    _PDFCreator.cOptions = opt;
                    _PDFCreator.cClearCache();

                    DefaultPrinter = _PDFCreator.cDefaultPrinter;

                    _PDFCreator.cDefaultPrinter = "PDFCreator";
                    oTimeOut.Interval = 120 * 1000;
                    oTimeOut.Enabled = true;
                    CLogger.MsgDebug("CPrintFile: " + fi.FullName);
                    _PDFCreator.cPrintFile(fi.FullName);
                    ReadyState = false;
                    _PDFCreator.cPrinterStop = false;
                    CLogger.MsgDebug("Espera máxima: " + oTimeOut.Interval.ToString());
                    while (!ReadyState && oTimeOut.Enabled)
                    {
                        //  Esperamos a que termine de imprimir 
                        // o a que salte el timer
                    }
                    CLogger.MsgDebug("HA TERMINADO DE IMPRIMIR");

                    oTimeOut.Enabled = false;
                    if (!ReadyState)
                    {
                        bResultado = false;
                        CLogger.MsgError("\nSE EXCEDIÓ EL TIEMPO DE IMPRESIÓN\n");
                    }

                    //_PDFCreator.cCombineAll();
                    _PDFCreator.cPrinterStop = true;
                    _PDFCreator.cDefaultPrinter = DefaultPrinter;

                    _PDFCreator.cClose();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(_PDFCreator);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pErr);
                    pErr = null;
                    GC.Collect();
                    GC.WaitForPendingFinalizers();

                    return bResultado;
                }
                else
                    return false;
            }
            catch (Exception e){

                CLogger.MsgError("ERROR AL ELIMINAR PDFCREATOR", e);

                if (_PDFCreator != null)
                    _PDFCreator = null;

                GC.Collect();
                GC.WaitForPendingFinalizers();
                return false;
            }
		}
Si hago pruebas para generar el informe, se abre el archivo excel y te aparece el típico mensaje de "¿Desea guardar los cambios efectuados en ....?". He de decir que el excel se genera a partir de una plantilla. En este punto se queda colgado el servicio y no hay manera de que prosiga con su ejecución. ¿Alguién sabe como hacer para que se acepte o se cancele dinámicamente este mensaje?

Muchas gracias
  #2 (permalink)  
Antiguo 13/05/2010, 06:24
Avatar de dmassive  
Fecha de Ingreso: febrero-2002
Ubicación: Paraná - Entre Ríos - Argentina
Mensajes: 279
Antigüedad: 22 años, 2 meses
Puntos: 7
Respuesta: c# Convertir EXCEL a PDF

Fijate si te sirve esto:
http://www.forosdelweb.com/f29/c-exp...ilidad-802408/
__________________
Blümchen... einfach die rave Prinzessin
http://www.dmassive.com.ar/
  #3 (permalink)  
Antiguo 14/05/2010, 04:34
 
Fecha de Ingreso: diciembre-2007
Ubicación: España
Mensajes: 51
Antigüedad: 16 años, 4 meses
Puntos: 1
Respuesta: c# Convertir EXCEL a PDF

Muchas gracias por tu respuesta, porque en este caso están exportando a EXCEL y yo estoy imprimiendo un archivo de EXCEL que ya existe a través del PDFCreator. El problema es que el PDFCreator me abre el EXCEL para convertirlo en PDF y luego me lo intenta cerrar y me aparece el mensaje de si desea guardar los cambios, pero yo en ningún momento manipulo el excel.

Muchas gracias

Última edición por tesitina; 14/05/2010 a las 04:40
  #4 (permalink)  
Antiguo 27/10/2011, 10:13
 
Fecha de Ingreso: enero-2007
Mensajes: 2
Antigüedad: 17 años, 3 meses
Puntos: 0
Respuesta: c# Convertir EXCEL a PDF

Estoy haciendo algo parecido, por no decir igual. A partir de una plantilla relleno los datos y luego ese xls (excel) creado lo quiero convertir a pdf con el pdfcreator (pero todo con codigo c#) pero el pedf creator al intentar abrir el excel, imprmierlo a pdf y cerrar el excel (tengo instalado el excel 2010) me dice el sigueinte mensaje
"Microsoft Excel actualiza las fórmulas al abrir archivos guardados con una version anterior de Excel" y me da tres opciones guardar, no guardar y cancelar. He intentado varias opciones pero no consigo nada.
Si alguien sabe como podria desactivar para que el excel 2010 no actualice nada de mi fichero xls generado con excel 2003??
Un saludo y gracias
  #5 (permalink)  
Antiguo 28/10/2011, 05:37
 
Fecha de Ingreso: enero-2007
Mensajes: 2
Antigüedad: 17 años, 3 meses
Puntos: 0
Respuesta: c# Convertir EXCEL a PDF

he encotrado la solucion a este problema. te pongo el link por si te sirve todavia. Se que es de hace mucho, pero... un saludo. y si no igual le sirve a otro

http://stackoverflow.com/questions/769246/xls-to-pdf-conversion-inside-net

el codigo correcto es en la parte que pone Office 2007 (pone numero 3 en el mensaje)

hay que bajarse el http://msdn.microsoft.com/en-us/library/kh3965hw.aspx

insertar la dll en el visual studio:

1. On the Project menu, click Add Reference.

2. On the COM tab, locate Microsoft Excel Object Library, and then click Select. In Visual Studio 2005, locate Microsoft Excel 11.0 Object Library on the COM tab.

3. Click OK in the Add References dialog box to accept your selections. If you are prompted to generate wrappers for the libraries that you selected, click “Yes”.

y luego copiar el codigo que pone en el post este:

Cita:
using System;
using System.IO;
using msExcel = Microsoft.Office.Interop.Excel;

namespace scpm {

public class ExcelToPdfConverter {

private static object missing = System.Reflection.Missing.Value;

public static void ConvertExcelToPdf(string excelFileIn, string pdfFileOut) {
msExcel.Application excel = new msExcel.Application();
try {
excel.Visible = false;
excel.ScreenUpdating = false;
excel.DisplayAlerts = false;

FileInfo excelFile = new FileInfo(excelFileIn);

string filename = excelFile.FullName;

msExcel.Workbook wbk = excel.Workbooks.Open(filename, missing,
missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing,
missing, missing, missing);
wbk.Activate();

object outputFileName = pdfFileOut;
msExcel.XlFixedFormatType fileFormat = msExcel.XlFixedFormatType.xlTypePDF;

// Save document into PDF Format
wbk.ExportAsFixedFormat(fileFormat, outputFileName,
missing, missing, missing,
missing, missing, missing,
missing);

object saveChanges = msExcel.XlSaveAction.xlDoNotSaveChanges;
((msExcel._Workbook)wbk).Close(saveChanges, missing, missing);
wbk = null;
}
finally {
((msExcel._Application)excel).Quit();
excel = null;
}
}

}
}
Espero que le sirva a alguien. A mi, tras varios dias intentando otras cosas al final he podido con esto!!

Un saludo

Etiquetas: excel, pdf
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 23:13.