bck
Alejandro Acuña
2024-11-11 f1cb4443aede6d4657bdc3396c8914d3a9f4fa93
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
package art.servers.rtzserver.reports;
 
import art.servers.ServerException;
import art.servers.rtzserver.Shared;
import art.servers.rtzserver.configuration.Configuration;
import com.sun.star.beans.PropertyValue;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XStorable;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.lib.uno.adapter.ByteArrayToXInputStreamAdapter;
import com.sun.star.lib.uno.adapter.OutputStreamToXOutputStreamAdapter;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import ooo.connector.BootstrapSocketConnector;
import ooo.connector.server.OOoServer;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
 
public class XLS 
{
    protected HSSFWorkbook workbook;
    protected String language = null;
    
    
    public XLS ()
    {
    }
    
    public XLS (File source) throws Exception
    {
        workbook = new HSSFWorkbook(new FileInputStream(source));
    }    
 
    
    
    public byte[] save(String format) throws Exception
    {
        if ((format.equalsIgnoreCase("xls")) || (format.equalsIgnoreCase("xlsx")) || (format.equalsIgnoreCase("xlsm")))
        {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            workbook.write(bos);
            byte[] xlsx = bos.toByteArray();
            bos.close();
            return xlsx;
        }
 
        if (format.equalsIgnoreCase("pdf"))
        {
            Shared.mutex.lockWrite();
            try
            {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                workbook.write(bos);
                byte[] xlsx = bos.toByteArray();
                bos.close();
                return toPDF(xlsx);
            } catch (Exception e)
            {
                throw e;
            } finally
            {
                Shared.mutex.releaseWrite();
            }
        }
        
        if (format.equalsIgnoreCase("csv"))
        {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            workbook.write(bos);
            byte[] xlsx = bos.toByteArray();
            bos.close();
            return toSCV(xlsx);
        }
        
        throw new Exception("Unknow format");
        
    }
    
    
    
    public byte[] saveAndClose(String format) throws Exception
    {   
        byte[] result = save(format);
        close();
        return result;
    }
    
    
    
    
    public void close ()
    {
        try
        {
            workbook.close();
        }
        catch (Exception e)
        {
        }
    }    
 
 
 
    
    // La primera columna e 1 y no 0
    
    private char[] chars = new char[] {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
 
    protected String columnName (int index)
    {
        index -= 1;
 
        int quotient = index / 26;
        if (quotient > 0)
        {
            return columnName(quotient) + chars[index % 26];
        }
        else
        {
            return "" + chars[index % 26];
        }
    }
 
    
  
    public void createRow (XSSFSheet hoja, int numeroFilaReferencia, int numeroFila) throws Exception
    {
        if (numeroFilaReferencia == numeroFila)  return;
        XSSFRow xssfrowReferencia = hoja.getRow(numeroFilaReferencia);
        XSSFRow xssfrow = hoja.createRow(numeroFila);
        xssfrow.setHeight(xssfrowReferencia.getHeight());
    }
    
    public void createRow (XSSFSheet sheet, int numeroFilaReferencia, int numeroFila, int numeroColumnas) throws Exception
    {
        createRow(sheet, numeroFilaReferencia, numeroFila, numeroColumnas, false);
    }
    
    
    public void createRow (XSSFSheet sheet, int numeroFilaReferencia, int numeroFila, int numeroColumnas, boolean copycontent) throws Exception
    {
        // Creamos la fila
 
        if (numeroFilaReferencia == numeroFila)  return;
        XSSFRow sourceRow = sheet.getRow(numeroFilaReferencia);
        XSSFRow destinationRow = sheet.createRow(numeroFila);
        destinationRow.setHeight(sourceRow.getHeight());
        
        for (int i=0; i<numeroColumnas; i++)
        {
            XSSFCell celda = destinationRow.createCell(i);
 
            if (sourceRow.getCell(i) != null)
            {
                celda.setCellStyle(sourceRow.getCell(i).getCellStyle());
 
                if (copycontent == true)
                {
                    copyValue(sourceRow.getCell(i), celda);
                }
            }
        }
        
        // If there are are any merged regions in the source row, copy to new row
        
        for (CellRangeAddress cellRangeAddress : sheet.getMergedRegions())
        {
                if (cellRangeAddress.getFirstRow() == sourceRow.getRowNum())
                {
                    try
                    {
                        CellRangeAddress  newCellRangeAddress = new CellRangeAddress
                        (    
                            destinationRow.getRowNum(),
                            (destinationRow.getRowNum() +
                            (cellRangeAddress.getFirstRow() -
                            cellRangeAddress.getLastRow())),
                            cellRangeAddress.getFirstColumn(),
                            cellRangeAddress.getLastColumn()
                        );
 
                        sheet.addMergedRegion(newCellRangeAddress);
                    }
                    catch (Exception e)
                    {
                    }
            }
        }        
    }
    
    
    public void copyValue (XSSFCell source, XSSFCell destination) throws Exception
    {
        if (source == null) return;
        if (destination == null) return;
 
        switch(source.getCellTypeEnum()) 
        {   
            case STRING:   
                 if (source.getStringCellValue().isEmpty() == false)
                 {
                    destination.setCellValue(source.getStringCellValue());   
                 }
                 break;   
            case NUMERIC:
                 destination.setCellValue(source.getNumericCellValue());   
                 break;   
            case BLANK:
                 destination.setCellType(CellType.BLANK);   
                 break;   
            case BOOLEAN: 
                 destination.setCellValue(source.getBooleanCellValue());   
                 break;   
            case ERROR:   
                 destination.setCellErrorValue(source.getErrorCellValue());   
                 break;   
            case FORMULA:   
                 destination.setCellFormula(source.getCellFormula());   
                 break;   
            default:   
                 break;   
        }               
    }
  
    
    
 
    public String getCellValueAsText (XSSFCell cell)
    {
        try
        {
            switch(cell.getCellTypeEnum()) 
            {   
                case STRING: return cell.getStringCellValue();
                case NUMERIC: return "" + (int)cell.getNumericCellValue();
                case BOOLEAN: return "" + cell.getBooleanCellValue(); 
                case FORMULA: return "" + cell.getCellFormula(); 
            }               
        }
        catch (Exception e)
        {
        }
        
        return "";
    }    
    
    
    
        
    public int getColumnWidth (XSSFSheet sheet, int col1, int col2) throws Exception
    {
        int result = 0;
        
        for (int i=col1; i<=col2; i++)
        {
            result = result + sheet.getColumnWidth(i);
        }
        
        return result;
    }
    
    
    public float getColumnWidthInPixels (XSSFSheet sheet, int col1, int col2) throws Exception
    {
        float result = 0;
        
        for (int i=col1; i<=col2; i++)
        {
            result = result + sheet.getColumnWidthInPixels(i);
        }
        
        return result;
    }
    
    
    
    
    
    public String getDate(long timestamp)
    {
        SimpleDateFormat ISO8601DATEFORMAT = new SimpleDateFormat(Shared.getMessage("yyyy-MM-dd HH:mm:ss"));
        ISO8601DATEFORMAT.setTimeZone(TimeZone.getDefault());
        return ISO8601DATEFORMAT.format(timestamp);
    }
    
 
    
    
    
    
    
    public int getNumberOfDays(long timestamp1, long timestamp2)
    {
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTimeInMillis(timestamp1);
        calendar1.set(Calendar.HOUR_OF_DAY,0);
        calendar1.set(Calendar.MINUTE,0);
        calendar1.set(Calendar.SECOND,0);
        calendar1.set(Calendar.MILLISECOND,0);
 
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTimeInMillis(timestamp2);
        calendar2.set(Calendar.HOUR_OF_DAY,0);
        calendar2.set(Calendar.MINUTE,0);
        calendar2.set(Calendar.SECOND,0);
        calendar2.set(Calendar.MILLISECOND,0);
        
        int numberOfDays = 0;
 
        do
        {
            numberOfDays = numberOfDays + 1;
            calendar1.add(Calendar.DATE, 1);
        }
        while(calendar1.getTimeInMillis() < calendar2.getTimeInMillis());
        
        
       return numberOfDays;
    }
    
    
 
    public void setBorder(XSSFSheet xssfsheet, CellRangeAddress cellRangeAddress, BorderStyle borderStyle)
    {
        RegionUtil.setBorderTop(borderStyle, cellRangeAddress, xssfsheet);
        RegionUtil.setBorderLeft(borderStyle, cellRangeAddress, xssfsheet);
        RegionUtil.setBorderBottom(borderStyle, cellRangeAddress, xssfsheet);
        RegionUtil.setBorderRight(borderStyle, cellRangeAddress, xssfsheet);
    }
    
    
 
    
    public byte[] toPDF(byte[] xlsx) throws ServerException, Exception
    {
 
        BootstrapSocketConnector bootstrapSocketConnector = null; 
        
        try
        {
            // Initialise
            String oooExeFolder = ((Configuration) Shared.configuration).detail.binaryPath;
            
            // Create OOo server with additional -nofirststartwizard option
            List oooOptions = new ArrayList();
            oooOptions.add("--nofirststartwizard");
            oooOptions.add("--headless");
            oooOptions.add("--nologo");
            oooOptions.add("--nodefault");
            oooOptions.add("--norestore");
            oooOptions.add("--nocrashreport");
            oooOptions.add("--nolockcheck");
            OOoServer oooServer = new OOoServer(oooExeFolder, oooOptions);
    
            // Connect to OOo
            bootstrapSocketConnector = new BootstrapSocketConnector(oooServer);
            
            XComponentContext remoteContext = bootstrapSocketConnector.connect("--accept=socket,host=localhost,port=8800;urp;","uno:socket,host=localhost,port=8800;urp;StarOffice.ComponentContext");
            
            XMultiComponentFactory remoteServiceManager = remoteContext.getServiceManager();
            
            Object desktop = remoteServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", remoteContext);
            
            XComponentLoader xComponentLoader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class,desktop);
 
            PropertyValue[] propertyValues = new PropertyValue[2];
            propertyValues[0] = new PropertyValue();
            propertyValues[0].Name = "Hidden";
            propertyValues[0].Value = new Boolean(true);
            propertyValues[1] = new PropertyValue();
            propertyValues[1].Name = "InputStream";
            propertyValues[1].Value = new ByteArrayToXInputStreamAdapter(xlsx);
            
            Object document = xComponentLoader.loadComponentFromURL("private:stream", "_blank", 0, propertyValues);
 
            // save as a PDF
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            XStorable xStorable = (XStorable) UnoRuntime.queryInterface(XStorable.class, document);
            propertyValues = new PropertyValue[3];
            propertyValues[0] = new PropertyValue();
            propertyValues[0].Name = "Overwrite";
            propertyValues[0].Value = new Boolean(true);
            propertyValues[1] = new PropertyValue();
            propertyValues[1].Name = "FilterName";
            propertyValues[1].Value = "writer_pdf_Export";
            propertyValues[2] = new PropertyValue();
            propertyValues[2].Name = "OutputStream";
            propertyValues[2].Value = new OutputStreamToXOutputStreamAdapter(bos);
            xStorable.storeToURL("private:stream", propertyValues);
 
            // Result 
            byte[] pdf = bos.toByteArray();
            bos.close();
 
            return pdf;
        } catch (Exception e)
        {
            Shared.printstack("XLSX", e);
            throw new Exception(Shared.getMessage(language, "Error generating pdf " + e.toString()));
        } finally
        {
            if(bootstrapSocketConnector != null)
            {
                 //Disconnect and terminate OOo server
                 bootstrapSocketConnector.disconnect();
            }
        }
    }
    
 
 
    
    public byte[] toSCV (byte[] xlsx) throws ServerException, Exception
    {
        try
        {
            HSSFFormulaEvaluator fe = workbook.getCreationHelper().createFormulaEvaluator();
            DataFormatter formatter = new DataFormatter();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            PrintStream out = new PrintStream(bos, true, "UTF-8");
            byte[] bom = {(byte)0xEF, (byte)0xBB, (byte)0xBF};
            {
                for (int i=0; i<workbook.getNumberOfSheets(); i++)
                {
                    HSSFSheet sheet = workbook.getSheetAt(i);
 
                    for (int r = 0, rn = sheet.getLastRowNum() ; r <= rn ; r++) 
                    {
                        HSSFRow row = sheet.getRow(r);
                        if ( row == null ) { out.println(';'); continue; }
                        boolean firstCell = true;
                        for (int c = 0, cn = row.getLastCellNum() ; c < cn ; c++) 
                        {
                            HSSFCell cell = row.getCell(c, HSSFRow.MissingCellPolicy.RETURN_BLANK_AS_NULL);
 
                            if (!firstCell) out.print(';');
 
                            try
                            {
                                if (cell != null) 
                                {
                                    if (cell.getCellTypeEnum() == CellType.BLANK) 
                                    {
                                        out.print("");
                                    }
                                    else if (cell.getCellTypeEnum() == CellType.BOOLEAN) 
                                    {
                                        out.print(cell.getBooleanCellValue());
                                    }
                                    else if (cell.getCellTypeEnum() == CellType.ERROR) 
                                    {
                                        out.print("");
                                    }
                                    else if (cell.getCellTypeEnum() == CellType.FORMULA) 
                                    {
                                        out.print(formatter.formatCellValue(fe.evaluateInCell(cell)));
                                    }
                                    else if (cell.getCellTypeEnum() == CellType.NUMERIC)
                                    {
                                        out.print(cell.getNumericCellValue());
                                    }
                                    else if (cell.getCellTypeEnum() == CellType.STRING)
                                    {
                                        out.print(cell.getStringCellValue());
                                    }
                                    else if (cell.getCellTypeEnum() == CellType._NONE)
                                    {
                                        out.print("");
                                    }
                                    else
                                    {
                                        out.print("");
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                            }
                            firstCell = false;
                        }
                        out.println();
                    }
                }
            }
 
            out.close();
            bos.close();
            return bos.toByteArray();
        }
        catch (Exception e)
        {
            throw new ServerException(Shared.getMessage(language, "Error generating csv"));
        }
    }    
 
    
    
 
    static private Pattern rxquote = Pattern.compile("\"");
 
    static private String encodeValue(String value) 
    {
        boolean needQuotes = false;
        if (value.indexOf(',') != -1 || value.indexOf('"') != -1 || value.indexOf('\n') != -1 || value.indexOf('\r') != -1)
        {
            needQuotes = true;
        }
        Matcher m = rxquote.matcher(value);
        if ( m.find() ) needQuotes = true; value = m.replaceAll("\"\"");
        if ( needQuotes ) return "\"" + value + "\"";
        else return value;
 
    }        
    
    
}