т.к. тема специфична разделу LS2J, пост разместил там, но, возможно, интересно будет и в общих задачах
https://codeby.net/threads/41201.html
https://codeby.net/threads/41201.html
Познакомьтесь с пентестом веб-приложений на практике в нашем новом бесплатном курсе
' openXLSObj.getWorkSheet(0).freezeRow(1) 'might be name error
openXLSObj.getWorkSheet(0).freezeCol(1) 'will freeze Row! but provide error message (in Excel)
Dim path As String, conf As String, confChild As String
path={D:\Documents\tmp\loan1.xlsm}
conf={Клиенты}
confChild={Платежи}
Dim config As New Config
Dim ioconf As New IOConfig(config, conf, path)
Dim ioconfChild As New IOConfig(config, confChild, path)
Set ioconf.Childs=ioconfChild
Call ioconf.Process()
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler;
import org.apache.poi.xssf.model.StylesTable;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.*;
/**
* Created by mike on 28.07.14.
*/
public class POI2CSV {
private final char SEP=';';
private class CSVmap {
private BufferedWriter osCSV;
private BufferedWriter osMAP;
public CSVmap(String xName) throws IOException {
osCSV= new BufferedWriter(new FileWriter(xName + ".csv"));
osMAP= new BufferedWriter(new FileWriter(xName + "_map" + ".csv"));
}
public void close() throws IOException {
osCSV.close();
osMAP.close();
}
public void write(String cellReference, String formattedValue) throws IOException {
// System.out.println(cellReference+SEP);
osMAP.write(cellReference + SEP);
osCSV.write(formattedValue + SEP);
}
public void newLine() throws IOException {
osMAP.newLine();
osCSV.newLine();
}
}
public void parseExcel(File file) throws IOException {
OPCPackage container;
try {
container = OPCPackage.open(file.getAbsolutePath());
ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(container);
XSSFReader xssfReader = new XSSFReader(container);
StylesTable styles = xssfReader.getStylesTable();
XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
while (iter.hasNext()) {
InputStream stream = iter.next();
//file.getName()+'_'+iter.getSheetName()
CSVmap csvmap=new CSVmap(file.getName()+'_'+iter.getSheetName());
processSheet(styles, strings, stream, csvmap);
stream.close();
csvmap.close();
}
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (OpenXML4JException e) {
e.printStackTrace();
}
}
protected void processSheet(StylesTable styles, ReadOnlySharedStringsTable strings, InputStream sheetInputStream, final CSVmap csvmap) throws IOException, SAXException {
InputSource sheetSource = new InputSource(sheetInputStream);
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
try {
SAXParser saxParser = saxFactory.newSAXParser();
XMLReader sheetParser = saxParser.getXMLReader();
ContentHandler handler = new XSSFSheetXMLHandler(styles, strings, new XSSFSheetXMLHandler.SheetContentsHandler() {
@Override
public void startRow(int rowNum) {
}
@Override
public void endRow() {
try {
csvmap.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void cell(String cellReference, String formattedValue) {
try {
csvmap.write(cellReference, formattedValue);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void headerFooter(String text, boolean isHeader, String tagName) {
}
},
false//means result instead of formula
);
sheetParser.setContentHandler(handler);
sheetParser.parse(sheetSource);
} catch (ParserConfigurationException e) {
throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage());}
}
public static void main(String args[]){
POI2CSV inst=new POI2CSV();
try {
System.out.println(args[0]);
inst.parseExcel(new File(args[0]));
} catch (IOException e) {
e.printStackTrace();
}
}
}
%REM
*********************************************
Class XLSXSAX
Description: Comments for Class
%END REM
Class XLSXSAX As ErrorHandlerWJ
Private POI2CSV As Javaclass
Private csvobj As Javaobject
Private sPath As String
%REM
*--------------------------------------------
Sub New
Description: Comments for Sub
%END REM
Sub New(xName As String)
Dim routineName As String
routineName="New"
On Error GoTo ErrH
'your code here
Set me.POI2CSV=jSession.Getclass({POI2CSV})
Set me.csvobj=me.POI2CSV.Createobject()
me.sPath=xName
Quit:
Exit Sub
ErrH:
Error Err, RaiseError
Resume Quit
End Sub
%REM
*--------------------------------------------
Function Process
Description: Comments for Function
%END REM
Function Process
Dim routineName As String
routineName="Process"
On Error GoTo ErrH
'your code here
Dim File, FileObj
Set File = jSession.GetClass({java/io/File})
Set FileObj= File.CreateObject({(Ljava/lang/String;)V}, me.sPath)
me.csvobj.parseExcel(FileObj)
' Process=
Quit:
Exit Function
ErrH:
Error Err, RaiseError
Resume Quit
End Function
%REM
*--------------------------------------------
Property Get arrPosMap
Description: Comments for Property Get
xName должно соответ. эленмету массива из
ArrPathMap
%END REM
Property Get ArrMap(xName As String) As Variant
Dim routineName As String
routineName="arrPosMap"
On Error GoTo ErrH
'your code here
ArrMap=me.csvobj.getArrMap(xName)
Quit:
Exit Property
ErrH:
Error Err, RaiseError
Resume Quit
End Property
%REM
*--------------------------------------------
Property Get arrPathMap
Description: Comments for Property Get
%END REM
Property Get ArrPathMap
Dim routineName As String
routineName="arrPathMap"
On Error GoTo ErrH
'your code here
ArrPathMap=me.csvobj.getArrPathMap()
Quit:
Exit Property
ErrH:
Error Err, RaiseError
Resume Quit
End Property
End Class
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler;
import org.apache.poi.xssf.model.StylesTable;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.*;
import java.util.*;
/**
* Created by mike on 28.07.14.
*/
public class POI2CSV {
private final String encoding="UTF-8";
private final Map<String,List<Integer>> arrPathCSV = new HashMap<String,List<Integer>>();
private final Map<String,List<Integer>> arrPathMap = new HashMap<String,List<Integer>>();
private class CSVmap {
private BufferedWriter osCSV;
private BufferedWriter osMAP;
private final File tempcsv;
private final File tempmap;
public CSVmap(String xName) throws IOException {
xName=xName.replaceAll("\"","");
tempcsv = File.createTempFile(xName, ".csv");
tempmap = File.createTempFile(xName, ".map");
osCSV= new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempcsv),encoding));
osMAP= new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempmap), encoding));
}
public void close() throws IOException {
osCSV.close();
osMAP.close();
}
public void write(String cellReference, String formattedValue) throws IOException {
// System.out.println(cellReference+SEP);
char SEP = ';';
osMAP.write(cellReference + SEP);
osCSV.write(formattedValue + SEP);
}
public void newLine() throws IOException {
osMAP.newLine();
osCSV.newLine();
}
public String getTempcsv() {
return tempcsv.getAbsolutePath();
}
public String getTempmap() {
return tempmap.getAbsolutePath();
}
}
public void parseExcel(File file) throws IOException {
OPCPackage container;
try {
container = OPCPackage.open(file.getAbsolutePath());
ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(container);
XSSFReader xssfReader = new XSSFReader(container);
StylesTable styles = xssfReader.getStylesTable();
XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
while (iter.hasNext()) {
InputStream stream = iter.next();
//file.getName()+'_'+iter.getSheetName()
CSVmap csvmap=new CSVmap(file.getName()+'_'+iter.getSheetName());
processSheet(styles, strings, stream, csvmap);
stream.close();
csvmap.close();
}
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (OpenXML4JException e) {
e.printStackTrace();
}
}
protected void processSheet(StylesTable styles, ReadOnlySharedStringsTable strings, InputStream sheetInputStream, final CSVmap csvmap) throws IOException, SAXException {
//duplicate for size in newLine
String lineSeparator = java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("line.separator"));
//length in bytes for default encoding, suppose UTF-8
final int lnsepLen=lineSeparator.getBytes(encoding).length;
final int sepLen=1;
InputSource sheetSource = new InputSource(sheetInputStream);
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
final List <Integer> arrmap=new ArrayList<Integer>(100);
final List<Integer> arrdata=new ArrayList<Integer>(100);
arrPathMap.put(csvmap.getTempmap(), arrmap);arrPathCSV.put(csvmap.getTempcsv(), arrdata);
try {
SAXParser saxParser = saxFactory.newSAXParser();
XMLReader sheetParser = saxParser.getXMLReader();
ContentHandler handler = new XSSFSheetXMLHandler(styles, strings, new XSSFSheetXMLHandler.SheetContentsHandler() {
int idx =0;//only one index for arrmap, arrdata
public void startRow(int rowNum) {
arrmap.add(0);arrdata.add(0);
idx =arrmap.size()-1;
}
public void endRow() {
try {
csvmap.newLine();
arrmap.set(idx,arrmap.get(idx) + lnsepLen);
arrdata.set(idx,arrdata.get(idx) + lnsepLen);
} catch (IOException e) {
e.printStackTrace();
}
}
public void cell(String cellReference, String formattedValue) {
try {
csvmap.write(cellReference, formattedValue);
//set data length for arrays
arrmap.set(idx,arrmap.get(idx) + cellReference.getBytes(encoding).length + sepLen);
arrdata.set(idx,arrdata.get(idx) + formattedValue.getBytes(encoding).length + sepLen);
} catch (IOException e) {
e.printStackTrace();
}
}
public void headerFooter(String text, boolean isHeader, String tagName) {
}
},
false//means result instead of formula
);
sheetParser.setContentHandler(handler);
sheetParser.parse(sheetSource);
} catch (ParserConfigurationException e) {
throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage());}
}
public Integer[] getArrMap(String key){
/* int[] ret= new int[arrmap.size()];
int i = 0;
for (Integer e : arrmap)
ret[i++] = e;
return ret;
*/
List <Integer> arr=arrPathMap.get(key);
return arr.toArray(new Integer[0]);
}
public Integer[] getArrData(String key){
List <Integer> arr=arrPathCSV.get(key);
return arr.toArray(new Integer[0]);
}
public String[] getArrPathCSV() {
Set<String> keys=arrPathCSV.keySet();
return keys.toArray(new String[0]);
}
public String[] getArrPathMap() {
Set<String> keys=arrPathMap.keySet();
return keys.toArray(new String[0]);
}
public static void main(String args[]){
POI2CSV inst=new POI2CSV();
try {
System.out.println(args[0]);
inst.parseExcel(new File(args[0]));
String[] mappath=inst.getArrPathMap();
String[] csvpath=inst.getArrPathCSV();
inst.getArrMap(mappath[0]);Integer[] test=inst.getArrData(csvpath[0]);
System.out.println(csvpath[0]);
System.out.println(test[0]);
} catch (IOException e) {
e.printStackTrace();
}
}
}
%REM
*********************************************
Agent test\1-SAX
Created Jul 29, 2014 by Mikhail Cholokov/CRUINTERNET
Description: Comments for Agent
%END REM
Option Public
Option Declare
Use "POI-Wrapper"
Sub Initialize
On Error GoTo ErrH
Dim csv As New XLSXSAX({D:/Documents/tmp/loan1.xlsm})
Call csv.Process()
Dim arrpath
arrpath=csv.arrPathMap()
Print {file for element #2:} &CStr(arrpath(2))
Dim arr As Variant
arr=csv.ArrMap(arrpath(2))
Print {pos for element #0:} &CStr(arr(0).intValue())
Quit:
Exit Sub
ErrH:
Error Err, RaiseError
Resume Quit
End Sub
Dim ses As New NotesSession
On Error GoTo ErrH
Dim csv As New XLSXSAX({D:/Documents/tmp/loan.xlsx})
Call csv.Process()
Dim arrpath,arrpathcsv, idx As Integer
idx=2
arrpath=csv.arrPathMap()
arrpathcsv=csv.ArrPathCSV()
Print {map file for element #2:} &CStr(arrpath(idx))
Print {csv file for element #2:} &CStr(arrpathcsv(idx))
Dim arrmap,arrdata
arrmap=csv.ArrMap(arrpath(idx))
Print {pos for element #0:} &CStr(arrmap(0).intValue())
Dim stream As NotesStream
Set stream=ses.Createstream()
Call stream.Open(arrpath(idx),{UTF-8})
stream.Position=arrmap(0).intValue()
Dim st As String
st=StrLeftBack(stream.ReadText(STMREAD_LINE), {;})
Print {cell ref arrays for 2-nd row>} &st
'для гарантированного сброса файловых буферов
Delete stream:Delete csv
'удаляем файлы
ForAll fmap In arrpath
Kill fmap
End ForAll
ForAll fcsv In arrpathcsv
Kill fcsv
End ForAll
Quit:
Exit Sub
ErrH:
Error Err, RaiseError
Resume Quit
Обучение наступательной кибербезопасности в игровой форме. Начать игру!