elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.


Tema destacado: ¿Eres nuevo? ¿Tienes dudas acerca del funcionamiento de la comunidad? Lee las Reglas Generales


  Mostrar Mensajes
Páginas: 1 ... 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 [696] 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 ... 1252
6951  Sistemas Operativos / Windows / Re: Ejecuto explorer.exe y no hace lo que debiera... en: 23 Agosto 2014, 20:19 pm
Nitro, tio, ¿a ti te parece que este tema va en Windows? xD.

Al parecer es algo común (bueno, que yo sepa solo me ha pasado a mi y ahora a ti xD), hasta la fecha no he podido identificar la causa del problema (he preguntado en sitios muy conocidos, olvida toda esperanza que tangas) pero probando alternativas llegué a una solución, eso si, en .NET:

[APORTE] Reinicializar el escritorio de forma correcta en Windows 8.1 cuando...
( En el post verás un enlace y dentro está el exe compilado, por si te sirve como solución alternativa de terceros )

No te fijes en el p/invoking y quédate con la parte importante del source:

Citar
Código
  1.    Dim Explorer As New Process With
  2.    {
  3.     .StartInfo = New ProcessStartInfo With
  4.                  {
  5.                   .FileName = Path.Combine(ExplorerDirectory, ExplorerFilename),
  6.                   .WorkingDirectory = My.Application.Info.DirectoryPath,
  7.                   .UseShellExecute = True,
  8.                   .CreateNoWindow = True
  9.                  }
  10.    }

Yo también estuve probando a ejecutarlo como parámetro de la CMD, etc, nada de eso funciona, solo eso me funcionó.

No manejo C++ pero intuyo que para reproducirlo puedes probar a utilizar la función CreateProcess y/o ShellExecuteEx de la WinAPI:
CreateProcess + STARTUPINFO structure
ShellExecuteEx  

Saludos
6952  Programación / Scripting / Re: Ayuda Mini-vbscript para aumentar/disminuir velocidad del raton DPI en: 23 Agosto 2014, 19:56 pm
decir que ya me ayudastes en su momento aunque no te acuerdes,con un bat para abrir un programa de television  :laugh:
Pues yo debo decirte que la verdad es que por el nick no me sonabas, pero ahora que dijiste eso ya lo recuerdo xD, creo que solo tu has expuesto ese tipo de problema (al menos en esta sección).

1
Código:
Wscript.Sleep 

Que segun tengo entendido pone el script en espera ,el tiempo que tu le digas en segundos 1500,2500....y luego sigue ejecutando.
Son milisegundos, no segundos. (por si acaso)



Yo lo que hice,fue visualmente  contar cuando pinchas main.cpl, y se abre ,tienes que darle al tabulador para cambiar entre las opciones, un total de 5 veces hasta llegar a la pestaña "Botones",luego dos veces a la derecha hasta llegar a la pestaña "Opciones de puntero" ,para luego darle 10 veces al tabulador hasta llegar al menu deseado,osea "Seleccione la velocidad del puntero",Lenta rapida ,pudiendo desplazarlos a la derecha o izquierda y darle a aceptar.

Lo que has echo es viajar por la ruta más larga.

Puedes abrir directamente la pestaña de las opciones de puntero.

Código
  1. Set Shell = CreateObject("WScript.Shell")
  2. Shell.Run "rundll32.exe shell32.dll,Control_RunDLL main.cpl,,2", False, False
  3.  
  4. Do Until IsProcessRunning("rundll32.exe") ' Esperar a que el proceso 'rundll32.exe' se haya inicializado.
  5. Wscript.Sleep 100
  6. Loop
  7.  
  8. Wscript.Sleep 1500 ' Esperar 1,5 segundos a que se cargue el Form del main.cpl (quizás puedas disminuirlo a 100 ms para ahorrar tiempo)
  9. Shell.SendKeys "{RIGHT}"
  10. Wscript.Sleep 100 ' Esperar entre 50-200 ms entre pulsacion y pulsacion por precaución.
  11. Shell.SendKeys "{ENTER}"
  12.  
  13. Wscript.Quit
  14.  
  15. ' By elektro
  16. Function IsProcessRunning(ProcessName)
  17.  
  18. IsProcessRunning = False
  19.  
  20. For Each Process In GetObject("winmgmts:").InstancesOf("Win32_Process")
  21.  
  22. If StrComp(Process.Name, ProcessName, 0) = 0 Then
  23. IsProcessRunning = True
  24. Exit for
  25. End If
  26.  
  27. Next
  28.  
  29. End Function

PD: Lo he testeado en Windows 8, pero si no recuerdo mal el menu en 7 y vista era idéntico.

EDITO: Ah, por cierto, si quieres aumentar al máximo o disminuir al mínimo la velocidad solo tienes que pulsar la tecla INICIO o FIN, no le vayas a dar repetidas veces a LEFT o RIGHT.

Citar
Hice la prueba con y sin Wscript.Sleep 2500 ,pero supongo que ahi que ponerle por lo menos 1 segundo o menos,nolose.

Eso es algo que no se puede determinar con exactitud, depende del tiempo que tarde tu hardware+so para procesar la pulsación, y también para dibujar los controles y el form. suelen ser pocos ms (no llega a 100) pero si tienes el equipo muuuuuy saturado entonces podría llegar a ser segundos, todo depende.

Saludos!
6953  Sistemas Operativos / Windows / Re: Barra que se instala en el navegador no puedo quitarla!! (No es babylon) en: 23 Agosto 2014, 18:41 pm
No era necesario el sarcamo  :-(

Quiero dejar clara una cosa:

Como ya indiqué te puse el enlace sin sarcasmo alguno, ¡no te lo tomes mal!, solo era para que vieses los términos de búsqueda utilicé, pienso que eso te podrá servir a observar mejor el problema si hubiera una próxima vez, pues muchas veces la gente suele volverse loca con este tipo de problemas, recurren a examinar las claves dle registro, exámenes de antivirus, pegar al PC xD, etc..., no encuentran solución y se desesperan, cuando lo más efectivo es recurrir a Google usando las palabras claves correctas (en este caso solo tomé el nombre base de la url que mostraste para buscar, y ya viste que fue algo efectivo para encontrar la solución al problema, a eso me refería).

Me alegro que lo hayas solucionado,
Saludos!
6954  Sistemas Operativos / Windows / Re: Barra que se instala en el navegador no puedo quitarla!! (No es babylon) en: 23 Agosto 2014, 16:30 pm
Aquí podrás encontrar algo util, por lo que veo hay infinidad de guias para eliminarlo http://bit.ly/1q6HKCO
(Sarcasmo OFF, es para que veas los términos de búsqueda que utilicé)

Saludos!
6955  Programación / .NET (C#, VB.NET, ASP) / Re: Convertir en binario a Hex y Decimal. en: 23 Agosto 2014, 16:23 pm
Quiero transformar estos valores binarios en Dec y Hex.

Código
  1. ' bin
  2. Dim binStr As String = String.Format("B{0}", "00000")
  3.  
  4. ' bin a hex
  5. Dim hexStr As String = String.Format("0x{0}", Convert.ToString(Convert.ToInt32(binStr.Replace("B"c, String.Empty), 2I), 16I))
  6.  
  7. ' hex a int32
  8. Dim decVal As String = Convert.ToInt32(hexStr, 16I)

Code Converter | Provided by Telerik
6956  Sistemas Operativos / Windows / Re: Problema con reinicio "personalizado" en windows 8.1 en: 23 Agosto 2014, 15:55 pm
¿Alguien sabe que ocurre?

Correcto  : DISABLE_INTEGRITY_CHECKS
Incorrecto: DDISABLE_INTEGRITY_CHECKS


Ten en cuenta que el parámetro loadoptions toma cualquier valor que escribas como si fuera correcto, pero en realidad lo pusiste mal.

Aparte, según un viejo código que estoy viendo en mi biblioteca de Batch, el valor del otro parámetro sería OFF, no ON (yo también me equivoqué ahí en el script de vbs).
Cita de: elektro
Código
  1. Echo [+] Desactivar la verificacion de drivers no firmados
  2. BCDEdit.exe /set "{current}" "loadoptions" "DISABLE_INTEGRITY_CHECKS"
  3. BCDEdit.exe /set "{current}" "TESTSIGNING" "OFF"

Saludos!
6957  Sistemas Operativos / Windows / Re: Problema con reinicio "personalizado" en windows 8.1 en: 23 Agosto 2014, 14:11 pm
Mi pregunta es como puedo cambiar las opciones de inicio del SO para que siempre se inicie con esa configuración.

Una vez hayas establecido la configuración desde la herramienta BCDEdit de Microsoft (o desde el menú del msconfig, que hace lo mismo) puedes exportar esa configuración a un archivo local, y entonces lo que podrías hacer es agregar una entrada a la sección 'RUN' del registro para importar esa configuración en cada siguiente reinicio.

Prueba con este Script, en VBS, he escrito unos comentarios en el código explicando el funcionamiento:

Código
  1. ' Permanently restart in Normal Mode with 'Driver Signature Enforcement' disabled.
  2. ' By Elektro
  3.  
  4. If Not Msgbox( _
  5. "¿Seguro que quieres reiniciar el equipo?", _
  6. 4 or 48, _
  7. "Reiniciar en Modo Normal con permiso de Drivers sin firma digital..." _
  8. ) = vbNo _
  9. Then
  10.  
  11. Set wshShell = WScript.CreateObject("WScript.Shell")
  12.  
  13. ' Elimino las opciones de la configuracióna ctual.
  14. wshShell.Run "bcdedit /deletevalue {current} loadoptions", 0, True
  15. wshShell.Run "bcdedit /deletevalue {current} safeboot"   , 0, True
  16.  
  17. ' Establezco las opciones de las firmas digitales de los Drivers.
  18. wshShell.Run "bcdedit /set {current} loadoptions DISABLE_INTEGRITY_CHECKS", 0, True
  19. wshShell.Run "bcdedit /set {current} TESTSIGNING OFF"                      , 0, True
  20.  
  21. ' Exporto la configuración actual a un archivo.
  22. TempFile = """" & wshShell.ExpandEnvironmentStrings("%WINDIR%\Bcdedit settings.bcd") & """"
  23. wshShell.Run "bcdedit /export " & TempFile, 0, True
  24.  
  25. ' Escribo una entrada de registro a la sección 'Run' para importar la configuración guardada en el archivo local,
  26. ' de esta manera la configuración se importará en cada siguiente reinicio.
  27. wshShell.RegWrite _
  28. "HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\*Import BCDEdit Settings - Unsigned Drivers",  _
  29. "bcdedit.exe /import " & TempFile, _
  30. "REG_SZ"
  31.        ' Nota: También se importará al reiniciar en modo seguro, para que esto no suceda elimina el caracter del asterisco al principio dle nombre de la clave.
  32.  
  33. wshShell.Run "shutdown -r -t 00 -f", 0, False
  34.  
  35. End If

Nota: No me culpes si algún programa se te bloquea por culpa de desactivar el chequeo de firmas o si sufres cualquier otro problema, no me hago responsable, por algo esta configuración debería usarse de forma temporal y no permanente.

PD: Te sugiero probarlo en una máquina virtual antes que en tu SO Host.
PD2: El código solo lo he escrito, no lo he testeado.

Saludos!
6958  Programación / Scripting / Re: Elimina archivos < 15 dias problema con rutas por espacios en: 23 Agosto 2014, 09:41 am
Antes de nada debo decir que ese script no es de buena calidad, la persona que lo escribió no tuvo los suficientes conocimientos ya que se basa en la utilización de un lenguaje inferior (Batch) y hace otras cosas innecesarias como la pausa de 2 segundos.



Citar
no encuentra la ruta si hay espacios

Las rutas con espacios deben encerrarse con comillas dobles: "C:\Ruta con espacios", bueno, en realidad TODO argumento debería encerrarse con las comillas dobles lleve espacios o no para no caer en malas practicas de uso, pero el caracter de la comila doble (") es un caracter reservado por el lenguaje VBS y se debe escapar, la manera de escaparla es duplicando el caracter ("").

Citar
Ah, tampoco se a que se refieren con Registros ...
Ni idea, es una variable que no está definida en el código, así que se tomará como un valor vacio:

Esto:
Código:
if objfso.getfile(fi).parentfolder.name <> Registros then...

Es lo mismo que:
Código:
If "Esto" es distinto a NADA then...
(Es decir, siempre dará positivo)

De todas formas al parecer la intención que tuvo con esa variable "desaparecida" es determinar si el archivo es realmente un archivo y no una carpeta, es algo innecesario porque puedes especificar la exclusión de carpetas en el comando de Batch.

Nota: Para evitar ese tipo de problemas con variables utiliza la declaración Option Explicit



El código corregido:

Código
  1. Option Explicit
  2. Dim Shell, FSO, FileList, File ' Objetos
  3. Dim Directory, OutputFile      ' Variables
  4.  
  5. Set Shell   = CreateObject( "WScript.Shell" )
  6. Set FSO     = createobject( "scripting.filesystemobject" )
  7.  
  8. Directory   = """" & "C:\users" & """"
  9. OutputFile  = """" & shell.ExpandEnvironmentStrings( "%TEMP%\" ) & "templist.txt" & """"
  10.  
  11. ' CMD.exe /C "Dir /B /S /A-D "Directorio" > "Archivo""
  12. Shell.run "CMD.exe /C ""DIR /B /S /A-D " & Directory & " > " & OutputFile & """", 0, 1
  13.  
  14. Set FileList = FSO.opentextfile(Replace(OutputFile, """", ""), 1)
  15.  
  16. 'abrimos el archivo temporal
  17. Do Until FileList.AtEndOfStream
  18.  
  19. 'leemos la siguiente linea del archivo
  20. Set File = FSO.GetFile(FileList.ReadLine)
  21.  
  22. 'revisamos la fecha y si tiene más de 15 dias (tomando en cuenta la fecha de hoy) entonces...
  23. If DateDiff("d", File.DateCreated,now()) > 15 Then
  24.  
  25. 'eliminamos el archivo.
  26. 'FSO.DeleteFile(File.Path)
  27.  
  28. End If
  29.  
  30. Loop
  31.  
  32. FileList.close ' Liberamos el objeto.

PD: Te recomiendo hacer una copia de seguridad del directorio antes de eliminar archivos, para comprobar que esté todo bien, pude tener algún fallo.

PD2: Como ya te expliqué el código no es de buena calidad, se puede obtener los archivos de forma recursiva utilizando VBS, lo cual es más eficiente, pero también requiere bastante más código, no se lo añadí por si eso te iba a confundir, pero en esta url tienes un ejemplo.

Saludos!
6959  Programación / .NET (C#, VB.NET, ASP) / Re: [Tutorial] Skins para C# en: 22 Agosto 2014, 20:42 pm
¿Porque demonios le cambiaste la extensión de las classes (.cs) a .txt?, no le encuentro sentido, es un estorbo xD.

 ¡ Por lo demás me parece un aporte genial !

Este aporte ha sido agregado al recopilatorio de temas interesantes

PD: Por si no lo saben, también pueden compilar las classes (quiero decir los "txt")  para agregar los controles al ToolBox y no tener que copiar y pegar en cada nuevo proyecto.

Saludos!
6960  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 22 Agosto 2014, 20:08 pm
Por algún motivo no me puedo instalar el MS Office así que tuve que buscar alguna alternativa para poder seguir desarrollando con manejo de Excel sin interop, y di con esta magnifica librería, NPOI:



http://npoi.codeplex.com/

Tomé los ejemplos oficiales en C# y escribí los siguientes ejemplos en VB.NET



Crear un workbook:

Código
  1. #Region " Create a WorkBook "
  2.  
  3.        ' Create the excel workbook.
  4.        Dim workbook As IWorkbook = New XSSFWorkbook()
  5.  
  6.        ' Create a sheet.
  7.        Dim sheet As ISheet = workbook.CreateSheet("Sheet A1")
  8.  
  9.        ' Create a cell.
  10.        Dim cell As ICell = sheet.CreateRow(0).CreateCell(0)
  11.  
  12.        ' Set cell value.
  13.        cell.SetCellValue("This is a test")
  14.  
  15.        ' Set the width of column A1.
  16.        sheet.SetColumnWidth(0, 50 * 256)
  17.  
  18.        ' Set the height of row A1.
  19.        sheet.CreateRow(0).Height = 200
  20.  
  21.        ' Save changes.
  22.        Using sw As IO.FileStream = IO.File.Create(".\Create a Workbook Example.xlsx")
  23.            workbook.Write(sw)
  24.        End Using
  25.  
  26. #End Region



Deinifir la cabecera y el pie de página:

Código
  1. #Region " Set Header and Footer "
  2.  
  3.    ' Create the excel workbook.
  4.    Dim workbook As IWorkbook = New XSSFWorkbook()
  5.    Dim sheet As ISheet = workbook.CreateSheet("Sheet1") ' Create a sheet.
  6.  
  7.    With sheet
  8.  
  9.    ' Create a cell and add a value.
  10.        .CreateRow(0).CreateCell(1).SetCellValue("test")
  11.  
  12.    ' Set header text.
  13.        .Header.Left = HSSFHeader.Page
  14.  
  15.    ' Page is a static property of HSSFHeader and HSSFFooter.
  16.        .Header.Center = "This is a test sheet"
  17.  
  18.    ' Set footer text.
  19.        .Footer.Left = "Copyright NPOI Team"
  20.        .Footer.Right = "created by Tony Qu&#65288;&#30655;&#26480;&#65289;"
  21.  
  22.    End With
  23.  
  24.     Save changes.
  25.    Using sw As IO.FileStream = IO.File.Create(".\Header-Footer Example.xlsx")
  26.        workbook.Write(sw)
  27.    End Using
  28.  
  29. #End Region



Añadir comentarios a una celda:

Código
  1. #Region " Add Comments "
  2.  
  3.    ' Create the excel workbook.
  4.    Dim workbook As IWorkbook = New XSSFWorkbook()
  5.    Dim sheet As ISheet = workbook.CreateSheet("some comments") ' Create the first sheet.
  6.  
  7.    ' Create the drawing patriarch. This is the top level container for all shapes including cell comments.
  8.    Dim patr As IDrawing = sheet.CreateDrawingPatriarch()
  9.  
  10.    ' Create a cell in row 3.
  11.    Dim cell1 As ICell = sheet.CreateRow(3).CreateCell(1)
  12.    cell1.SetCellValue(New XSSFRichTextString("Hello, World"))
  13.  
  14.    ' Create a richtext to use it in the comment.
  15.    Dim strComment As New XSSFRichTextString("This is saying you hello")
  16.  
  17.    ' Create the richtext font style.
  18.    Dim font As IFont = workbook.CreateFont()
  19.    With font
  20.        .FontName = "Arial"
  21.        .FontHeightInPoints = 10
  22.        .Boldweight = CShort(FontBoldWeight.Bold)
  23.        .Color = HSSFColor.Red.Index
  24.    End With
  25.  
  26.    ' Apply font style to the text in the comment.
  27.    strComment.ApplyFont(font)
  28.  
  29.    ' Create a comment, Anchor defines size and position of the comment in worksheet.
  30.    Dim comment1 As IComment = patr.CreateCellComment(New XSSFClientAnchor(0, 0, 0, 0, 4, 2, 6, 5))
  31.    With comment1
  32.  
  33.    ' Set comment text.
  34.        .[String] = strComment
  35.  
  36.    ' Set comment author.
  37.        .Author = "Elektro"
  38.  
  39.    ' By default comments are hidden. This one is always visible.
  40.        .Visible = True
  41.  
  42.    End With
  43.  
  44.    '* The first way to assign comment to a cell is via CellComment method:
  45.    cell1.CellComment = comment1
  46.    '* The second way to assign comment to a cell is to implicitly specify its row and column.
  47.    '* Note: It is possible to set row and column of a non-existing cell.
  48.    comment1.Row = 3
  49.    comment1.Column = 1
  50.  
  51.    ' Save changes.
  52.    Using sw As IO.FileStream = IO.File.Create(".\Comment Example.xlsx")
  53.        workbook.Write(sw)
  54.    End Using
  55.  
  56. #End Region



Definir propiedades personalizadas:

Código
  1. #Region " Set Custom Properties "
  2.  
  3.    ' Create the excel workbook.
  4.    Dim workbook As XSSFWorkbook = New XSSFWorkbook()
  5.    Dim sheet As ISheet = workbook.CreateSheet("Sheet1") ' Create the first sheet.
  6.  
  7.    ' Get the properties.
  8.    Dim props As POIXMLProperties = workbook.GetProperties()
  9.  
  10.    With props ' Set some default properties.
  11.        .CoreProperties.Title = "Properties Example"
  12.        .CoreProperties.Creator = "Elektro"
  13.        .CoreProperties.Created = DateTime.Now
  14.    End With
  15.  
  16.    ' Set a custom property.
  17.    If Not props.CustomProperties.Contains("My Property Name") Then
  18.        props.CustomProperties.AddProperty("My Property Name", "Hello World!")
  19.    End If
  20.  
  21.    ' Save changes.
  22.    Using sw As IO.FileStream = IO.File.Create(".\Properties Example.xlsx")
  23.        workbook.Write(sw)
  24.    End Using
  25.  
  26. #End Region



Rellenar el color de fondo de una celda:

Código
  1. #Region " Fill Cell Background "
  2.  
  3.    ' Create the excel workbook.
  4.    Dim workbook As IWorkbook = New XSSFWorkbook()
  5.  
  6.    ' Create a sheet.
  7.    Dim sheet As ISheet = workbook.CreateSheet("Sheet1")
  8.  
  9.    ' Create a cell.
  10.    Dim cell1 As ICell = sheet.CreateRow(0).CreateCell(0)
  11.  
  12.    ' Set the cell text.
  13.    cell1.SetCellValue("Hello")
  14.  
  15.    ' Set the Background Style.
  16.    Dim style As ICellStyle = workbook.CreateCellStyle()
  17.    With style
  18.        .FillForegroundColor = IndexedColors.Blue.Index
  19.        .FillPattern = FillPattern.BigSpots
  20.        .FillBackgroundColor = IndexedColors.Pink.Index
  21.    End With
  22.  
  23.    ' Fill the cell background.
  24.    cell1.CellStyle = style
  25.  
  26.    ' Save changes.
  27.    Using sw As IO.FileStream = IO.File.Create(".\Fill background Example.xlsx")
  28.        workbook.Write(sw)
  29.    End Using
  30.  
  31. #End Region



Añadir un hyperlink:

Código
  1. #Region " Add HyperLinks "
  2.  
  3.    ' Create the excel workbook.
  4.    Dim workbook As IWorkbook = New XSSFWorkbook()
  5.    Dim cell As ICell = Nothing
  6.    Dim sheet As ISheet = workbook.CreateSheet("Hyperlinks") ' Create the first sheet.
  7.  
  8.    ' Set the Hyperlink style.
  9.    Dim HyperLinkStyle As ICellStyle = workbook.CreateCellStyle()
  10.    Dim HyperLinkFont As IFont = workbook.CreateFont()
  11.    HyperLinkFont.Underline = FontUnderlineType.[Single]
  12.    HyperLinkFont.Color = HSSFColor.Blue.Index
  13.    HyperLinkStyle.SetFont(HyperLinkFont)
  14.  
  15.    ' Link to an URL.
  16.    Dim LinkURL As New XSSFHyperlink(HyperlinkType.Url) With {.Address = "http://poi.apache.org/"}
  17.    cell = sheet.CreateRow(0).CreateCell(0)
  18.    With cell
  19.        .SetCellValue("URL Link")
  20.        .Hyperlink = LinkURL
  21.        .CellStyle = HyperLinkStyle
  22.    End With
  23.  
  24.    ' Link to a file.
  25.    Dim LinkFile As New XSSFHyperlink(HyperlinkType.File) With {.Address = "link1.xls"}
  26.    cell = sheet.CreateRow(1).CreateCell(0)
  27.    With cell
  28.        .SetCellValue("File Link")
  29.        .Hyperlink = LinkFile
  30.        .CellStyle = HyperLinkStyle
  31.    End With
  32.  
  33.    ' Link to an e-amil.
  34.    Dim LinkMail As New XSSFHyperlink(HyperlinkType.Email) With {.Address = "mailto:poi@apache.org?subject=Hyperlinks"}
  35.    With cell
  36.        cell = sheet.CreateRow(2).CreateCell(0)
  37.        .SetCellValue("Email Link")
  38.        .Hyperlink = LinkMail
  39.        .CellStyle = HyperLinkStyle
  40.    End With
  41.  
  42.    ' Link to a place in the workbook.
  43.    Dim LinkSheet As New XSSFHyperlink(HyperlinkType.Document) With {.Address = "'Target ISheet'!A1"}
  44.    Dim sheet2 As ISheet = workbook.CreateSheet("Target ISheet") ' Create a target sheet.
  45.    sheet2.CreateRow(0).CreateCell(0).SetCellValue("Target ICell") ' Create a target cell.
  46.    With cell
  47.        cell = sheet.CreateRow(3).CreateCell(0)
  48.        .SetCellValue("Worksheet Link")
  49.        .Hyperlink = LinkSheet
  50.        .CellStyle = HyperLinkStyle
  51.    End With
  52.  
  53.    ' Save changes.
  54.    Using sw As IO.FileStream = IO.File.Create(".\HyperLink Example.xlsx")
  55.        workbook.Write(sw)
  56.    End Using
  57.  
  58. #End Region



Establecer el estilo de fuente:

Código
  1. #Region " Set Font style "
  2.  
  3.    ' Create the excel workbook.
  4.    Dim workbook As IWorkbook = New XSSFWorkbook()
  5.    Dim sheet1 As ISheet = workbook.CreateSheet("Sheet1") ' Create the first sheet.
  6.  
  7.    ' Create a cell style.
  8.    Dim style1 As ICellStyle = workbook.CreateCellStyle()
  9.  
  10.    ' Create a font style.
  11.    Dim font1 As IFont = workbook.CreateFont()
  12.    With font1 ' underlined, italic, red color, fontsize=20
  13.        .Color = IndexedColors.Red.Index
  14.        .IsItalic = True
  15.        .Underline = FontUnderlineType.[Double]
  16.        .FontHeightInPoints = 20
  17.    End With
  18.  
  19.    ' bind font1 with style1
  20.    style1.SetFont(font1)
  21.  
  22.    ' Create a cell, add text, and apply the font.
  23.    Dim cell1 As ICell = sheet1.CreateRow(1).CreateCell(1)
  24.    With cell1
  25.        .SetCellValue("Hello World!")
  26.        .CellStyle = style1
  27.    End With
  28.  
  29.    ' Save changes.
  30.    Using sw As IO.FileStream = IO.File.Create(".\Font-Style Example.xlsx")
  31.        workbook.Write(sw)
  32.    End Using
  33.  
  34. #End Region



Establecer el tipo de fuente para texto con formato (rich text):

Código
  1. #Region " Set Font style RichText "
  2.  
  3.    ' Create the excel workbook.
  4.    Dim workbook As IWorkbook = New XSSFWorkbook()
  5.    Dim sheet1 As ISheet = workbook.CreateSheet("Sheet1") ' Create the first sheet.
  6.  
  7.    ' Create a cell with rich text.
  8.    Dim cell1 As ICell = sheet1.CreateRow(0).CreateCell(0)
  9.  
  10.    ' Create a richtext.
  11.    Dim richtext As New XSSFRichTextString("Microsoft OfficeTM")
  12.  
  13.    ' Create a font style.
  14.    Dim font1 As IFont = workbook.CreateFont()
  15.    With font1
  16.        .FontHeightInPoints = 12
  17.    End With
  18.    richtext.ApplyFont(0, 16, font1) ' apply font to "Microsoft Office".
  19.  
  20.    ' Create a font style.
  21.    Dim font2 As IFont = workbook.CreateFont()
  22.    With font2
  23.        .TypeOffset = FontSuperScript.Super
  24.        .IsItalic = True
  25.        .Color = IndexedColors.Blue.Index
  26.        .FontHeightInPoints = 8
  27.    End With
  28.    richtext.ApplyFont(16, 18, font2) ' apply font to "TM"
  29.  
  30.    ' Add the richtext into the cell.
  31.    cell1.SetCellValue(richtext)
  32.  
  33.    ' Save changes.
  34.    Using sw As IO.FileStream = IO.File.Create(".\Font-Style RichText Example.xlsx")
  35.        workbook.Write(sw)
  36.    End Using
  37.  
  38. #End Region



Añadir una tabla:

Código
  1. #Region " Add a Table "
  2.  
  3.    ' Create the excel workbook.
  4.    Dim workbook As IWorkbook = New XSSFWorkbook()
  5.    Dim sheet1 As XSSFSheet = DirectCast(workbook.CreateSheet("Sheet1"), XSSFSheet) ' Create the first sheet.
  6.  
  7.    ' Create a cell with text.
  8.    sheet1.CreateRow(0).CreateCell(0).SetCellValue("This is a Sample")
  9.  
  10.    ' Create a table.
  11.    Dim x As Integer = 1
  12.    For i As Integer = 1 To 15
  13.    Dim row As IRow = sheet1.CreateRow(i)
  14.        For j As Integer = 0 To 14
  15.            row.CreateCell(j).SetCellValue(System.Math.Max(System.Threading.Interlocked.Increment(x), x - 1))
  16.        Next j
  17.    Next i
  18.    Dim table As XSSFTable = sheet1.CreateTable()
  19.    table.Name = "Tabella1"
  20.    table.DisplayName = "Tabella1"
  21.  
  22.    ' Save changes.
  23.    Using sw As IO.FileStream = IO.File.Create(".\Table Example.xlsx")
  24.        workbook.Write(sw)
  25.    End Using
  26.  
  27. #End Region



Formatear el valor de una celda:

Código
  1. #Region " Format Cell Data "
  2.  
  3.    Private Sub Test() Handles MyBase.Shown
  4.  
  5.        ' Create the excel workbook.
  6.        Dim workbook As IWorkbook = New XSSFWorkbook()
  7.  
  8.        ' Create a sheet.
  9.        Dim sheet As ISheet = workbook.CreateSheet("Sheet1")
  10.  
  11.        ' Create the format instance.
  12.        Dim format As IDataFormat = workbook.CreateDataFormat()
  13.  
  14.        ' Increase the width of Column A.
  15.        sheet.SetColumnWidth(0, 5000)
  16.  
  17.        ' Create a row and put some cells in it. Rows are 0 based.
  18.        Dim cell1 As ICell = sheet.CreateRow(0).CreateCell(0)
  19.        Dim cell2 As ICell = sheet.CreateRow(1).CreateCell(0)
  20.        Dim cell3 As ICell = sheet.CreateRow(2).CreateCell(0)
  21.        Dim cell4 As ICell = sheet.CreateRow(3).CreateCell(0)
  22.        Dim cell5 As ICell = sheet.CreateRow(4).CreateCell(0)
  23.        Dim cell6 As ICell = sheet.CreateRow(5).CreateCell(0)
  24.        Dim cell7 As ICell = sheet.CreateRow(6).CreateCell(0)
  25.  
  26.        ' Format the cell values.
  27.  
  28.        ' [Cell1]
  29.        ' Number format with 2 digits after the decimal point. eg: "1.20"
  30.        SetValueAndFormat(workbook, cell1, 1.2, HSSFDataFormat.GetBuiltinFormat("0.00"))
  31.  
  32.        ' [Cell2]
  33.        ' RMB currency format with comma. eg: "¥20,000"
  34.        SetValueAndFormat(workbook, cell2, 20000, format.GetFormat("¥#,##0"))
  35.  
  36.        ' [Cell3]
  37.        ' Scentific number format. eg: "3.15E+00"
  38.        SetValueAndFormat(workbook, cell3, 3.151234, format.GetFormat("0.00E+00"))
  39.  
  40.        ' [Cell4]
  41.        ' Percent format, 2 digits after the decimal point. eg: "99.33%"
  42.        SetValueAndFormat(workbook, cell4, 0.99333, format.GetFormat("0.00%"))
  43.  
  44.        ' [Cell5]
  45.        ' Phone number format. eg: "021-65881234"
  46.        SetValueAndFormat(workbook, cell5, 2165881234UI, format.GetFormat("000-00000000"))
  47.  
  48.        ' [Cell6]:
  49.        ' Formula value with datetime style.
  50.        cell6.CellFormula = "DateValue(""2005-11-11"")+TIMEVALUE(""11:11:11"")"
  51.        Dim cellStyle6 As ICellStyle = workbook.CreateCellStyle()
  52.        cellStyle6.DataFormat = HSSFDataFormat.GetBuiltinFormat("m/d/yy h:mm")
  53.        cell6.CellStyle = cellStyle6
  54.  
  55.        ' [Cell7]:
  56.        ' Display current time in AM/PM format.
  57.        SetDate(workbook, cell7, DateTime.Now, format.GetFormat("[$-409]h:mm:ss AM/PM;@"))
  58.  
  59.        ' Save changes.
  60.        Using sw As IO.FileStream = IO.File.Create(".\Formula Example.xlsx")
  61.            workbook.Write(sw)
  62.        End Using
  63.  
  64.    End Sub
  65.  
  66.    Private Shared Sub SetValueAndFormat(ByVal workbook As IWorkbook,
  67.                                         ByVal cell As ICell,
  68.                                         ByVal value As Double,
  69.                                         ByVal formatId As Short)
  70.  
  71.        cell.SetCellValue(value)
  72.        Dim cellStyle As ICellStyle = workbook.CreateCellStyle()
  73.        cellStyle.DataFormat = formatId
  74.        cell.CellStyle = cellStyle
  75.  
  76.    End Sub
  77.  
  78.    Private Shared Sub SetDate(ByVal workbook As IWorkbook,
  79.                               ByVal cell As ICell,
  80.                               ByVal value As DateTime,
  81.                               ByVal formatId As Short)
  82.  
  83.        'set value for the cell
  84.        If Not value = Nothing Then
  85.            cell.SetCellValue(value)
  86.        End If
  87.  
  88.        Dim cellStyle As ICellStyle = workbook.CreateCellStyle()
  89.        cellStyle.DataFormat = formatId
  90.        cell.CellStyle = cellStyle
  91.  
  92.    End Sub
  93.  
  94. #End Region



Ocultar una fila o una columna:

Código
  1. #Region " Hide row or column "
  2.  
  3.    ' Create the excel workbook.
  4.    Dim workbook As IWorkbook = New XSSFWorkbook()
  5.  
  6.    ' Create a sheet.
  7.    Dim sheet As ISheet = workbook.CreateSheet("Sheet1")
  8.  
  9.    ' Create some rows.
  10.    Dim r1 As IRow = sheet.CreateRow(0)
  11.    Dim r2 As IRow = sheet.CreateRow(1)
  12.    Dim r3 As IRow = sheet.CreateRow(2)
  13.    Dim r4 As IRow = sheet.CreateRow(3)
  14.    Dim r5 As IRow = sheet.CreateRow(4)
  15.  
  16.    ' Hide IRow 2.
  17.    r2.ZeroHeight = True
  18.  
  19.    ' Hide column C.
  20.    sheet.SetColumnHidden(2, True)
  21.  
  22.    ' Save changes.
  23.    Using sw As IO.FileStream = IO.File.Create(".\Hide Row or Column Example.xlsx")
  24.        workbook.Write(sw)
  25.    End Using
  26.  
  27. #End Region



Añadir una imagen:

Código
  1.        ' Create the excel workbook.
  2.        Dim workbook As IWorkbook = New XSSFWorkbook()
  3.  
  4.        ' Create a sheet.
  5.        Dim sheet As ISheet = workbook.CreateSheet("PictureSheet")
  6.  
  7.        ' Create the drawing patriarch. This is the top level container for all shapes including cell comments.
  8.        Dim patriarch As IDrawing = sheet.CreateDrawingPatriarch()
  9.  
  10.        ' Create the anchor.
  11.        Dim anchor As New XSSFClientAnchor(500, 200, 0, 0, 2, 2, 4, 7)
  12.        anchor.AnchorType = 2
  13.  
  14.        ' Load the picture and get the picture index in the workbook.
  15.        Dim imageId As Integer = LoadImage("C:\Users\Administrador\Desktop\4t0n.png", workbook)
  16.        Dim picture As XSSFPicture = DirectCast(patriarch.CreatePicture(anchor, imageId), XSSFPicture)
  17.  
  18.        ' Reset the image to the original size.
  19.        ' Note: Resize will reset client anchor you set.
  20.        'picture.Resize();  
  21.  
  22.        ' Save changes.
  23.        Using sw As IO.FileStream = IO.File.Create(".\Add Picture Example.xlsx")
  24.            workbook.Write(sw)
  25.        End Using
  26.  
  27.  
  28.    Public Shared Function LoadImage(path As String, wb As IWorkbook) As Integer
  29.        Dim file As New FileStream(path, FileMode.Open, FileAccess.Read)
  30.        Dim buffer As Byte() = New Byte(file.Length - 1) {}
  31.        file.Read(buffer, 0, CInt(file.Length))
  32.        Return wb.AddPicture(buffer, PictureType.JPEG)
  33.    End Function



Unir celdas:

Código
  1.        ' Create the excel workbook.
  2.        Dim workbook As IWorkbook = New XSSFWorkbook()
  3.  
  4.        ' Create a sheet.
  5.        Dim sheet As ISheet = workbook.CreateSheet("Sheet1")
  6.  
  7.        ' Create a cell.
  8.        Dim cell As ICell = sheet.CreateRow(1).CreateCell(1)
  9.        cell.SetCellValue(New XSSFRichTextString("This is a test of merging"))
  10.  
  11.        ' Merge B2 cell with C2 cell.
  12.        sheet.AddMergedRegion(New CellRangeAddress(1, 1, 1, 2))
  13.  
  14.        ' Save changes.
  15.        Using sw As IO.FileStream = IO.File.Create(".\Merge Cells Example.xlsx")
  16.            workbook.Write(sw)
  17.        End Using



Proteger con contraseña:

Código
  1.        ' Create the excel workbook.
  2.        Dim workbook As IWorkbook = New XSSFWorkbook()
  3.  
  4.        ' Create a sheet.
  5.        Dim sheet As XSSFSheet = DirectCast(workbook.CreateSheet("Sheet A1"), XSSFSheet)
  6.  
  7.        With sheet ' Lock accessing excel operations.
  8.            .LockFormatRows()
  9.            .LockFormatCells()
  10.            .LockFormatColumns()
  11.            .LockDeleteColumns()
  12.            .LockDeleteRows()
  13.            .LockInsertHyperlinks()
  14.            .LockInsertColumns()
  15.            .LockInsertRows()
  16.        End With
  17.  
  18.        ' Set the password to unprotect:
  19.        Dim password As String = "Your Password"
  20.        sheet.ProtectSheet(password)
  21.  
  22.        ' Save changes.
  23.        Using sw As IO.FileStream = IO.File.Create(".\Protect Cells Example.xlsx")
  24.            workbook.Write(sw)
  25.        End Using


EDITO:


Como leer un workbook:

Código
  1.        ' The existing workbook filepath.
  2.        Dim WorkBookFile As String = "C:\MyWorkBook.xlsx"
  3.  
  4.        ' Create the excel workbook instance.
  5.        Dim workbook As IWorkbook = Nothing
  6.  
  7.        ' Load the workbook.
  8.        Using file As New IO.FileStream(WorkBookFile, IO.FileMode.Open, IO.FileAccess.Read)
  9.            workbook = New XSSFWorkbook(file)
  10.        End Using
  11.  
  12.        ' Get the first sheet.
  13.        Dim sheet As ISheet = workbook.GetSheetAt(0)
  14.  
  15.        ' Get the first row.
  16.        Dim row As IRow = sheet.GetRow(0)
  17.  
  18.        ' Create a cell.
  19.        Dim cell As ICell = row.CreateCell(1)
  20.  
  21.        ' Get the cell value.
  22.        If String.IsNullOrEmpty(cell.StringCellValue) Then ' If value is emty then...
  23.  
  24.            ' Set cell value.
  25.            cell.SetCellValue("This is a test")
  26.  
  27.        End If
  28.  
  29.        ' Save changes.
  30.        Using sw As IO.FileStream = IO.File.Create(WorkBookFile)
  31.            workbook.Write(sw)
  32.        End Using
Páginas: 1 ... 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 [696] 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 ... 1252
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines