|
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: Dim Explorer As New Process With { .StartInfo = New ProcessStartInfo With { .FileName = Path.Combine(ExplorerDirectory, ExplorerFilename), .WorkingDirectory = My.Application.Info.DirectoryPath, .UseShellExecute = True, .CreateNoWindow = True } }
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  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 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. Set Shell = CreateObject("WScript.Shell") Shell.Run "rundll32.exe shell32.dll,Control_RunDLL main.cpl,,2", False, False Do Until IsProcessRunning("rundll32.exe") ' Esperar a que el proceso 'rundll32.exe' se haya inicializado. Wscript.Sleep 100 Loop 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) Shell.SendKeys "{RIGHT}" Wscript.Sleep 100 ' Esperar entre 50-200 ms entre pulsacion y pulsacion por precaución. Shell.SendKeys "{ENTER}" Wscript.Quit ' By elektro Function IsProcessRunning(ProcessName) IsProcessRunning = False For Each Process In GetObject("winmgmts:").InstancesOf("Win32_Process") If StrComp(Process.Name, ProcessName, 0) = 0 Then IsProcessRunning = True Exit for End If Next 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. 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!
|
|
|
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_CHECKSTen 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). Echo [+] Desactivar la verificacion de drivers no firmados BCDEdit.exe / set "{current}" "loadoptions" "DISABLE_INTEGRITY_CHECKS" 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: ' Permanently restart in Normal Mode with 'Driver Signature Enforcement' disabled. ' By Elektro If Not Msgbox( _ "¿Seguro que quieres reiniciar el equipo?", _ 4 or 48, _ "Reiniciar en Modo Normal con permiso de Drivers sin firma digital..." _ ) = vbNo _ Then Set wshShell = WScript.CreateObject("WScript.Shell") ' Elimino las opciones de la configuracióna ctual. wshShell.Run "bcdedit /deletevalue {current} loadoptions", 0, True wshShell.Run "bcdedit /deletevalue {current} safeboot" , 0, True ' Establezco las opciones de las firmas digitales de los Drivers. wshShell.Run "bcdedit /set {current} loadoptions DISABLE_INTEGRITY_CHECKS", 0, True wshShell.Run "bcdedit /set {current} TESTSIGNING OFF" , 0, True ' Exporto la configuración actual a un archivo. TempFile = """" & wshShell.ExpandEnvironmentStrings("%WINDIR%\Bcdedit settings.bcd") & """" wshShell.Run "bcdedit /export " & TempFile, 0, True ' Escribo una entrada de registro a la sección 'Run' para importar la configuración guardada en el archivo local, ' de esta manera la configuración se importará en cada siguiente reinicio. wshShell.RegWrite _ "HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\*Import BCDEdit Settings - Unsigned Drivers", _ "bcdedit.exe /import " & TempFile, _ "REG_SZ" ' 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. wshShell.Run "shutdown -r -t 00 -f", 0, False 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.
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 ( ""). 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: if objfso.getfile(fi).parentfolder.name <> Registros then... Es lo mismo que: 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: Option Explicit Dim Shell, FSO, FileList, File ' Objetos Dim Directory, OutputFile ' Variables Set Shell = CreateObject( "WScript.Shell" ) Set FSO = createobject( "scripting.filesystemobject" ) Directory = """" & "C:\users" & """" OutputFile = """" & shell.ExpandEnvironmentStrings( "%TEMP%\" ) & "templist.txt" & """" ' CMD.exe /C "Dir /B /S /A-D "Directorio" > "Archivo"" Shell.run "CMD.exe /C ""DIR /B /S /A-D " & Directory & " > " & OutputFile & """", 0, 1 Set FileList = FSO.opentextfile(Replace(OutputFile, """", ""), 1) 'abrimos el archivo temporal Do Until FileList.AtEndOfStream 'leemos la siguiente linea del archivo Set File = FSO.GetFile(FileList.ReadLine) 'revisamos la fecha y si tiene más de 15 dias (tomando en cuenta la fecha de hoy) entonces... If DateDiff("d", File.DateCreated,now()) > 15 Then 'eliminamos el archivo. 'FSO.DeleteFile(File.Path) End If Loop 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 interesantesPD: 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: #Region " Create a WorkBook " ' Create the excel workbook. Dim workbook As IWorkbook = New XSSFWorkbook() ' Create a sheet. Dim sheet As ISheet = workbook.CreateSheet("Sheet A1") ' Create a cell. Dim cell As ICell = sheet.CreateRow(0).CreateCell(0) ' Set cell value. cell.SetCellValue("This is a test") ' Set the width of column A1. sheet.SetColumnWidth(0, 50 * 256) ' Set the height of row A1. sheet.CreateRow(0).Height = 200 ' Save changes. Using sw As IO. FileStream = IO. File. Create(".\Create a Workbook Example.xlsx") workbook.Write(sw) End Using #End Region
Deinifir la cabecera y el pie de página: #Region " Set Header and Footer " ' Create the excel workbook. Dim workbook As IWorkbook = New XSSFWorkbook() Dim sheet As ISheet = workbook.CreateSheet("Sheet1") ' Create a sheet. With sheet ' Create a cell and add a value. .CreateRow(0).CreateCell(1).SetCellValue("test") ' Set header text. .Header.Left = HSSFHeader.Page ' Page is a static property of HSSFHeader and HSSFFooter. .Header.Center = "This is a test sheet" ' Set footer text. .Footer.Left = "Copyright NPOI Team" .Footer.Right = "created by Tony Qu(瞿杰)" End With Save changes. Using sw As IO. FileStream = IO. File. Create(".\Header-Footer Example.xlsx") workbook.Write(sw) End Using #End Region
Añadir comentarios a una celda: #Region " Add Comments " ' Create the excel workbook. Dim workbook As IWorkbook = New XSSFWorkbook() Dim sheet As ISheet = workbook.CreateSheet("some comments") ' Create the first sheet. ' Create the drawing patriarch. This is the top level container for all shapes including cell comments. Dim patr As IDrawing = sheet.CreateDrawingPatriarch() ' Create a cell in row 3. Dim cell1 As ICell = sheet.CreateRow(3).CreateCell(1) cell1.SetCellValue(New XSSFRichTextString("Hello, World")) ' Create a richtext to use it in the comment. Dim strComment As New XSSFRichTextString("This is saying you hello") ' Create the richtext font style. Dim font As IFont = workbook.CreateFont() With font .FontName = "Arial" .FontHeightInPoints = 10 .Boldweight = CShort(FontBoldWeight.Bold) .Color = HSSFColor.Red.Index End With ' Apply font style to the text in the comment. strComment.ApplyFont(font) ' Create a comment, Anchor defines size and position of the comment in worksheet. Dim comment1 As IComment = patr.CreateCellComment(New XSSFClientAnchor(0, 0, 0, 0, 4, 2, 6, 5)) With comment1 ' Set comment text. .[String] = strComment ' Set comment author. .Author = "Elektro" ' By default comments are hidden. This one is always visible. .Visible = True End With '* The first way to assign comment to a cell is via CellComment method: cell1.CellComment = comment1 '* The second way to assign comment to a cell is to implicitly specify its row and column. '* Note: It is possible to set row and column of a non-existing cell. comment1.Row = 3 comment1.Column = 1 ' Save changes. Using sw As IO. FileStream = IO. File. Create(".\Comment Example.xlsx") workbook.Write(sw) End Using #End Region
Definir propiedades personalizadas: #Region " Set Custom Properties " ' Create the excel workbook. Dim workbook As XSSFWorkbook = New XSSFWorkbook() Dim sheet As ISheet = workbook.CreateSheet("Sheet1") ' Create the first sheet. ' Get the properties. Dim props As POIXMLProperties = workbook.GetProperties() With props ' Set some default properties. .CoreProperties.Title = "Properties Example" .CoreProperties.Creator = "Elektro" .CoreProperties.Created = DateTime.Now End With ' Set a custom property. If Not props.CustomProperties.Contains("My Property Name") Then props.CustomProperties.AddProperty("My Property Name", "Hello World!") End If ' Save changes. Using sw As IO. FileStream = IO. File. Create(".\Properties Example.xlsx") workbook.Write(sw) End Using #End Region
Rellenar el color de fondo de una celda: #Region " Fill Cell Background " ' Create the excel workbook. Dim workbook As IWorkbook = New XSSFWorkbook() ' Create a sheet. Dim sheet As ISheet = workbook.CreateSheet("Sheet1") ' Create a cell. Dim cell1 As ICell = sheet.CreateRow(0).CreateCell(0) ' Set the cell text. cell1.SetCellValue("Hello") ' Set the Background Style. Dim style As ICellStyle = workbook.CreateCellStyle() With style .FillForegroundColor = IndexedColors.Blue.Index .FillPattern = FillPattern.BigSpots .FillBackgroundColor = IndexedColors.Pink.Index End With ' Fill the cell background. cell1.CellStyle = style ' Save changes. Using sw As IO. FileStream = IO. File. Create(".\Fill background Example.xlsx") workbook.Write(sw) End Using #End Region
Añadir un hyperlink: #Region " Add HyperLinks " ' Create the excel workbook. Dim workbook As IWorkbook = New XSSFWorkbook() Dim cell As ICell = Nothing Dim sheet As ISheet = workbook.CreateSheet("Hyperlinks") ' Create the first sheet. ' Set the Hyperlink style. Dim HyperLinkStyle As ICellStyle = workbook.CreateCellStyle() Dim HyperLinkFont As IFont = workbook.CreateFont() HyperLinkFont.Underline = FontUnderlineType.[Single] HyperLinkFont.Color = HSSFColor.Blue.Index HyperLinkStyle.SetFont(HyperLinkFont) ' Link to an URL. Dim LinkURL As New XSSFHyperlink(HyperlinkType.Url) With {.Address = "http://poi.apache.org/"} cell = sheet.CreateRow(0).CreateCell(0) With cell .SetCellValue("URL Link") .Hyperlink = LinkURL .CellStyle = HyperLinkStyle End With ' Link to a file. Dim LinkFile As New XSSFHyperlink (HyperlinkType. File) With {. Address = "link1.xls"} cell = sheet.CreateRow(1).CreateCell(0) With cell .SetCellValue("File Link") .Hyperlink = LinkFile .CellStyle = HyperLinkStyle End With ' Link to an e-amil. Dim LinkMail As New XSSFHyperlink(HyperlinkType.Email) With {.Address = "mailto:poi@apache.org?subject=Hyperlinks"} With cell cell = sheet.CreateRow(2).CreateCell(0) .SetCellValue("Email Link") .Hyperlink = LinkMail .CellStyle = HyperLinkStyle End With ' Link to a place in the workbook. Dim LinkSheet As New XSSFHyperlink(HyperlinkType.Document) With {.Address = "'Target ISheet'!A1"} Dim sheet2 As ISheet = workbook.CreateSheet("Target ISheet") ' Create a target sheet. sheet2.CreateRow(0).CreateCell(0).SetCellValue("Target ICell") ' Create a target cell. With cell cell = sheet.CreateRow(3).CreateCell(0) .SetCellValue("Worksheet Link") .Hyperlink = LinkSheet .CellStyle = HyperLinkStyle End With ' Save changes. Using sw As IO. FileStream = IO. File. Create(".\HyperLink Example.xlsx") workbook.Write(sw) End Using #End Region
Establecer el estilo de fuente: #Region " Set Font style " ' Create the excel workbook. Dim workbook As IWorkbook = New XSSFWorkbook() Dim sheet1 As ISheet = workbook.CreateSheet("Sheet1") ' Create the first sheet. ' Create a cell style. Dim style1 As ICellStyle = workbook.CreateCellStyle() ' Create a font style. Dim font1 As IFont = workbook.CreateFont() With font1 ' underlined, italic, red color, fontsize=20 .Color = IndexedColors.Red.Index .IsItalic = True .Underline = FontUnderlineType.[Double] .FontHeightInPoints = 20 End With ' bind font1 with style1 style1.SetFont(font1) ' Create a cell, add text, and apply the font. Dim cell1 As ICell = sheet1.CreateRow(1).CreateCell(1) With cell1 .SetCellValue("Hello World!") .CellStyle = style1 End With ' Save changes. Using sw As IO. FileStream = IO. File. Create(".\Font-Style Example.xlsx") workbook.Write(sw) End Using #End Region
Establecer el tipo de fuente para texto con formato (rich text): #Region " Set Font style RichText " ' Create the excel workbook. Dim workbook As IWorkbook = New XSSFWorkbook() Dim sheet1 As ISheet = workbook.CreateSheet("Sheet1") ' Create the first sheet. ' Create a cell with rich text. Dim cell1 As ICell = sheet1.CreateRow(0).CreateCell(0) ' Create a richtext. Dim richtext As New XSSFRichTextString("Microsoft OfficeTM") ' Create a font style. Dim font1 As IFont = workbook.CreateFont() With font1 .FontHeightInPoints = 12 End With richtext.ApplyFont(0, 16, font1) ' apply font to "Microsoft Office". ' Create a font style. Dim font2 As IFont = workbook.CreateFont() With font2 .TypeOffset = FontSuperScript.Super .IsItalic = True .Color = IndexedColors.Blue.Index .FontHeightInPoints = 8 End With richtext.ApplyFont(16, 18, font2) ' apply font to "TM" ' Add the richtext into the cell. cell1.SetCellValue(richtext) ' Save changes. Using sw As IO. FileStream = IO. File. Create(".\Font-Style RichText Example.xlsx") workbook.Write(sw) End Using #End Region
Añadir una tabla: #Region " Add a Table " ' Create the excel workbook. Dim workbook As IWorkbook = New XSSFWorkbook() Dim sheet1 As XSSFSheet = DirectCast(workbook.CreateSheet("Sheet1"), XSSFSheet) ' Create the first sheet. ' Create a cell with text. sheet1.CreateRow(0).CreateCell(0).SetCellValue("This is a Sample") ' Create a table. Dim x As Integer = 1 For i As Integer = 1 To 15 Dim row As IRow = sheet1.CreateRow(i) For j As Integer = 0 To 14 row.CreateCell(j).SetCellValue(System.Math.Max(System.Threading.Interlocked.Increment(x), x - 1)) Next j Next i Dim table As XSSFTable = sheet1.CreateTable() table.Name = "Tabella1" table.DisplayName = "Tabella1" ' Save changes. Using sw As IO. FileStream = IO. File. Create(".\Table Example.xlsx") workbook.Write(sw) End Using #End Region
Formatear el valor de una celda: #Region " Format Cell Data " Private Sub Test() Handles MyBase.Shown ' Create the excel workbook. Dim workbook As IWorkbook = New XSSFWorkbook() ' Create a sheet. Dim sheet As ISheet = workbook.CreateSheet("Sheet1") ' Create the format instance. Dim format As IDataFormat = workbook.CreateDataFormat() ' Increase the width of Column A. sheet.SetColumnWidth(0, 5000) ' Create a row and put some cells in it. Rows are 0 based. Dim cell1 As ICell = sheet.CreateRow(0).CreateCell(0) Dim cell2 As ICell = sheet.CreateRow(1).CreateCell(0) Dim cell3 As ICell = sheet.CreateRow(2).CreateCell(0) Dim cell4 As ICell = sheet.CreateRow(3).CreateCell(0) Dim cell5 As ICell = sheet.CreateRow(4).CreateCell(0) Dim cell6 As ICell = sheet.CreateRow(5).CreateCell(0) Dim cell7 As ICell = sheet.CreateRow(6).CreateCell(0) ' Format the cell values. ' [Cell1] ' Number format with 2 digits after the decimal point. eg: "1.20" SetValueAndFormat(workbook, cell1, 1.2, HSSFDataFormat.GetBuiltinFormat("0.00")) ' [Cell2] ' RMB currency format with comma. eg: "¥20,000" SetValueAndFormat(workbook, cell2, 20000, format.GetFormat("¥#,##0")) ' [Cell3] ' Scentific number format. eg: "3.15E+00" SetValueAndFormat(workbook, cell3, 3.151234, format.GetFormat("0.00E+00")) ' [Cell4] ' Percent format, 2 digits after the decimal point. eg: "99.33%" SetValueAndFormat(workbook, cell4, 0.99333, format.GetFormat("0.00%")) ' [Cell5] ' Phone number format. eg: "021-65881234" SetValueAndFormat(workbook, cell5, 2165881234UI, format.GetFormat("000-00000000")) ' [Cell6]: ' Formula value with datetime style. cell6.CellFormula = "DateValue(""2005-11-11"")+TIMEVALUE(""11:11:11"")" Dim cellStyle6 As ICellStyle = workbook.CreateCellStyle() cellStyle6.DataFormat = HSSFDataFormat.GetBuiltinFormat("m/d/yy h:mm") cell6.CellStyle = cellStyle6 ' [Cell7]: ' Display current time in AM/PM format. SetDate(workbook, cell7, DateTime.Now, format.GetFormat("[$-409]h:mm:ss AM/PM;@")) ' Save changes. Using sw As IO. FileStream = IO. File. Create(".\Formula Example.xlsx") workbook.Write(sw) End Using End Sub Private Shared Sub SetValueAndFormat(ByVal workbook As IWorkbook, ByVal cell As ICell, ByVal value As Double, ByVal formatId As Short) cell.SetCellValue(value) Dim cellStyle As ICellStyle = workbook.CreateCellStyle() cellStyle.DataFormat = formatId cell.CellStyle = cellStyle End Sub Private Shared Sub SetDate(ByVal workbook As IWorkbook, ByVal cell As ICell, ByVal value As DateTime, ByVal formatId As Short) 'set value for the cell If Not value = Nothing Then cell.SetCellValue(value) End If Dim cellStyle As ICellStyle = workbook.CreateCellStyle() cellStyle.DataFormat = formatId cell.CellStyle = cellStyle End Sub #End Region
Ocultar una fila o una columna: #Region " Hide row or column " ' Create the excel workbook. Dim workbook As IWorkbook = New XSSFWorkbook() ' Create a sheet. Dim sheet As ISheet = workbook.CreateSheet("Sheet1") ' Create some rows. Dim r1 As IRow = sheet.CreateRow(0) Dim r2 As IRow = sheet.CreateRow(1) Dim r3 As IRow = sheet.CreateRow(2) Dim r4 As IRow = sheet.CreateRow(3) Dim r5 As IRow = sheet.CreateRow(4) ' Hide IRow 2. r2.ZeroHeight = True ' Hide column C. sheet.SetColumnHidden(2, True) ' Save changes. Using sw As IO. FileStream = IO. File. Create(".\Hide Row or Column Example.xlsx") workbook.Write(sw) End Using #End Region
Añadir una imagen: ' Create the excel workbook. Dim workbook As IWorkbook = New XSSFWorkbook() ' Create a sheet. Dim sheet As ISheet = workbook.CreateSheet("PictureSheet") ' Create the drawing patriarch. This is the top level container for all shapes including cell comments. Dim patriarch As IDrawing = sheet.CreateDrawingPatriarch() ' Create the anchor. Dim anchor As New XSSFClientAnchor(500, 200, 0, 0, 2, 2, 4, 7) anchor.AnchorType = 2 ' Load the picture and get the picture index in the workbook. Dim imageId As Integer = LoadImage("C:\Users\Administrador\Desktop\4t0n.png", workbook) Dim picture As XSSFPicture = DirectCast(patriarch.CreatePicture(anchor, imageId), XSSFPicture) ' Reset the image to the original size. ' Note: Resize will reset client anchor you set. 'picture.Resize(); ' Save changes. Using sw As IO. FileStream = IO. File. Create(".\Add Picture Example.xlsx") workbook.Write(sw) End Using Public Shared Function LoadImage(path As String, wb As IWorkbook) As Integer Dim file As New FileStream (path, FileMode. Open, FileAccess. Read) Dim buffer As Byte() = New Byte(file. Length - 1) {} Return wb.AddPicture(buffer, PictureType.JPEG) End Function
Unir celdas: ' Create the excel workbook. Dim workbook As IWorkbook = New XSSFWorkbook() ' Create a sheet. Dim sheet As ISheet = workbook.CreateSheet("Sheet1") ' Create a cell. Dim cell As ICell = sheet.CreateRow(1).CreateCell(1) cell.SetCellValue(New XSSFRichTextString("This is a test of merging")) ' Merge B2 cell with C2 cell. sheet.AddMergedRegion(New CellRangeAddress(1, 1, 1, 2)) ' Save changes. Using sw As IO. FileStream = IO. File. Create(".\Merge Cells Example.xlsx") workbook.Write(sw) End Using
Proteger con contraseña: ' Create the excel workbook. Dim workbook As IWorkbook = New XSSFWorkbook() ' Create a sheet. Dim sheet As XSSFSheet = DirectCast(workbook.CreateSheet("Sheet A1"), XSSFSheet) With sheet ' Lock accessing excel operations. .LockFormatRows() .LockFormatCells() .LockFormatColumns() .LockDeleteColumns() .LockDeleteRows() .LockInsertHyperlinks() .LockInsertColumns() .LockInsertRows() End With ' Set the password to unprotect: Dim password As String = "Your Password" sheet.ProtectSheet(password) ' Save changes. Using sw As IO. FileStream = IO. File. Create(".\Protect Cells Example.xlsx") workbook.Write(sw) End Using
EDITO:Como leer un workbook: ' The existing workbook filepath. Dim WorkBookFile As String = "C:\MyWorkBook.xlsx" ' Create the excel workbook instance. Dim workbook As IWorkbook = Nothing ' Load the workbook. Using file As New IO. FileStream(WorkBookFile, IO. FileMode. Open, IO. FileAccess. Read) workbook = New XSSFWorkbook (file) End Using ' Get the first sheet. Dim sheet As ISheet = workbook.GetSheetAt(0) ' Get the first row. Dim row As IRow = sheet.GetRow(0) ' Create a cell. Dim cell As ICell = row.CreateCell(1) ' Get the cell value. If String.IsNullOrEmpty(cell.StringCellValue) Then ' If value is emty then... ' Set cell value. cell.SetCellValue("This is a test") End If ' Save changes. Using sw As IO. FileStream = IO. File. Create(WorkBookFile ) workbook.Write(sw) End Using
|
|
|
|
|
|
|