Insert datetime in Excel with JSP - excel

I've the below JSP to insert values into Excel.
<%#page import="java.util.Locale"%>
<%#page import="java.text.SimpleDateFormat"%>
<%#page import="java.sql.*"%>
<%
Connection con = null;
Statement stmt = null;
java.util.Date dt=new java.util.Date();
try {
String a = request.getParameter("comments");
String b = request.getParameter("updatedl");
String c = request.getParameter("sid");
String d = request.getParameter("desc");
String e = request.getParameter("pubcode");
String f = request.getParameter("Type");
String g = request.getParameter("status");
String h = null;
if (null != request.getParameter("DateRec")) {
h = request.getParameter("DateRec");
}
String i = null;
if (null != request.getParameter("startD")) {
i = request.getParameter("startD");
}
String j = null;
if (null != request.getParameter("AssignedD")) {
j = request.getParameter("AssignedD");
}
String k = null;
if (null != request.getParameter("sentToAE")) {
k = request.getParameter("sentToAE");
}
String l = null;
if (null != request.getParameter("RespFrmAE")) {
l = request.getParameter("RespFrmAE");
}
String m = null;
if (null != request.getParameter("VWRCmp")) {
m = request.getParameter("VWRCmp");
}
String n = request.getParameter("PS");
String o = request.getParameter("TEst");
String p = request.getParameter("Units");
String q = null;
if (null != request.getParameter("VWR")) {
q = request.getParameter("VWR");
}
String r = request.getParameter("IE");
String s = null;
if (null != request.getParameter("RevDate")) {
s = request.getParameter("RevDate");
}
String t = request.getParameter("ReviewS");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Excel Driver (*.xls)};DBQ=C:/jus/Excel1.xls; ReadOnly=true;");
String query = null;
String columnString = new String();
String values = new String();
columnString = "insert into [Feb$] ([comments],[No of lines updated in PSIS],[Shipment ID],"
+ "[SAP TXT Description],[Phoenix Pub Code], [Product Type]" ;
values = " values("+ a + "," + b + "," + c + ",'" + d + "','" + e + "','" + f + "'";
out.println("h value "+n);
if(null!= g && !g.isEmpty()){
columnString = columnString+(",[Status of the job]");
values = values + ",'" +g;
}
if(null!= n && !n.isEmpty()){
columnString = columnString+(",[Assigned to PS]");
values = values + "','" +n;
}
if(null!= o && !o.isEmpty()){
columnString = columnString+(",[Time Estimate]");
values = values + "','" +o;
}
if(null!= p && !p.isEmpty()){
columnString = columnString+(",[Units]");
values = values + "','" +p;
}
if(null!= r && !r.isEmpty()){
columnString = columnString+(",[Internal Errors]");
values = values + "','" +r;
}
if(null!= t && !t.isEmpty()){
columnString = columnString+(",[Review Sent (Yes/No)]");
values = values + "','" +t;
}
if(null!= h && !h.isEmpty()){
columnString = columnString+(",[Date Request received]");
values = values + "','" +h;
}
if(null!= i && !i.isEmpty()){
columnString = columnString+(",[Start Date]");
values = values + "','" +i;
}
if(null!= j && !j.isEmpty()){
columnString = columnString+(",[Date assigned]");
values = values + "','" +j;
}
if(null!= k && !k.isEmpty()){
columnString = columnString+(",[Date file sent to AE]");
values = values + "','" +k;
}
if(null!= l&& !l.isEmpty()){
columnString = columnString+(",[Date response from AE]");
values = values + "','" +l;
}
if(null!= m && !m.isEmpty()){
columnString = columnString+(",[Date completed --VWR]");
values = values + "','" +m;
}
if(null!= q && !q.isEmpty()){
columnString = columnString+(",[Date file needs to be sent to Vendor (VWR)]");
values = values + "','" +q;
}
if(null!= s && !s.isEmpty()){
columnString = columnString+(",[Review Date]");
values = values + "','" +s;
}
columnString = columnString+")";
values = values + "')";
query = columnString+values;
out.println(query);
PreparedStatement ps = con.prepareStatement(query);
int new1 = ps.executeUpdate();
String UR = "success.jsp";
response.sendRedirect(UR);
} catch (Exception e) {
out.println(e);
} finally {
try {
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
%>
Here the date fields that I'm accessing is getting values from a jquery datepicker in my previous html page, but now I want to concatenate this date with current time and insert in Excel sheet, when I try to concatenate like below, it is giving me an exception.
if(null!= h && !h.isEmpty()){
columnString = columnString+(",[Date Request received]");
values = values + "','" +h+dt;
}
the exception I'm getting is as below.
java.sql.SQLException: [Microsoft][ODBC Excel Driver] Data type mismatch in criteria expression.
please let me know how can i achieve this.
Thanks

Related

Single Speechmarks not added to numbers

I have the below Code which works, except for if there is a number in the text field so a single speech mark does not get added around say 1 but would be around one.
As an aside I don't want speechmarks on the first column (the ID value)
SEP = ", "
QUOTE = "\'"
NEWLINE = System.getProperty("line.separator")
KEYWORDS_LOWERCASE = com.intellij.database.util.DbSqlUtil.areKeywordsLowerCase(PROJECT)
KW_INSERT_INTO = KEYWORDS_LOWERCASE ? "insert into " : "INSERT INTO "
KW_VALUES = KEYWORDS_LOWERCASE ? ") values (" : ") VALUES ("
KW_NULL = KEYWORDS_LOWERCASE ? "null" : "NULL"
def record(columns, dataRow) {
OUT.append(KW_INSERT_INTO)
if (TABLE == null) OUT.append("MY_TABLE")
else OUT.append(TABLE.getParent().getName()).append(".").append(TABLE.getName())
OUT.append(" (")
columns.eachWithIndex { column, idx ->
OUT.append(column.name()).append(idx != columns.size() - 1 ? SEP : "")
}
OUT.append(KW_VALUES)
columns.eachWithIndex { column, idx ->
def value = dataRow.value(column)
def stringValue = value != null ? FORMATTER.format(dataRow, column) : KW_NULL
if (DIALECT.getDbms().isMysql())
stringValue = stringValue.replace("\\", "\\\\")
OUT.append(skipQuote ? "": QUOTE).append(stringValue.replace(QUOTE, QUOTE + QUOTE))
.append(skipQuote ? "": QUOTE).append(idx != columns.size() - 1 ? SEP : "")
}
OUT.append(");").append(NEWLINE)
}
ROWS.each { row -> record(COLUMNS, row) }
Not 100% sure what and why you are trying to achieve, but I would write down something like that in idiomatic groovy:
LinkedHashMap.metaClass.value = { delegate.get it } // mock value()
TABLE = [ parent:[ name:'OTHER_TABLE' ] ] // fake TABLE
KEYWORDS_LOWERCASE = true // false
KW_INSERT_INTO = 'INSERT INTO'
KW_VALUES = 'VALUES'
if( KEYWORDS_LOWERCASE ){
KW_INSERT_INTO = KW_INSERT_INTO.toLowerCase()
KW_VALUES = KW_VALUES.toLowerCase()
}
COLUMNS = [ 'a', 'nullllll', 'c', 'numberString' ]
String record(columns, dataRow) {
List values = columns.collect{
def v = dataRow.value it
switch( v ){
case Number:
case ~/\d+/: return v
case String: return "'$v'"
default: return 'null'
}
}
"$KW_INSERT_INTO ${TABLE?.parent?.name ?: 'MY_TABLE'} (${columns.join( ', ' )}) $KW_VALUES (${values.join( ', ' )});\n"
}
String res = record( COLUMNS, [ a:'aa', c:42, numberString:'84' ] )
assert res == "insert into OTHER_TABLE (a, nullllll, c, numberString) values ('aa', null, 42, 84);\n"
In switch statement the values are getting formatted.
You can try out yourself at https://groovyconsole.appspot.com/script/5151418931478528

pretty printing from any format to a desired format

I am wondering if there is a way by which I can convert a format, let's say a tree to a format I want. Take the following example:
a -> b, d
f - > c
f-> v
I want to have this as an output:
a implies (b and d)
f implies (c or v)
This is practically the algorithm that you are looking for, but please take note that this algorithm doesn't support the deep conditions.
function mathLogic(inputs) {
var rows = inputs.split("\n");
for (var i in rows)
rows[i] = rows[i].replace(/\s/g, "");
console.log("Rows: ", rows)
var logics = {};
for (var i in rows) {
var row = rows[i];
var rowSplit = row.split("->");
var from = rowSplit[0];
var to = rowSplit[1];
var ands = to.split(",");
if (!logics[from])
logics[from] = [];
logic = logics[from];
logic.push(ands);
}
for (var i in logics) {
var implyString = i + " implies ";
var orLogic = logics[i];
var ors = [];
for (var j in orLogic) {
var or = orLogic[j]
if (or.length > 1)
ors.push("(" + or.join(" and ") + ")");
else
ors.push(or.join(" and "));
}
if (ors.length > 1)
implyString += "(" + ors.join(" or ") + ")";
else
implyString += ors.join(" or ");
console.log(implyString);
}
}
mathLogic(`a -> b, d
f - > c
f-> v`);

CSV file parsing in C#

Wanted to check if there is any null value in column field in the csv file and also there shouldn't be null value after / in number column, if it is null the entire row should not be written to output file.
name,number,gender,country
iva 1/001 f Antartica
aaju 2/002 m russia
lax 3/ m brazil
ana 4/004 f Thailand
vis 5/005 m
for e.g. 3rd and 5th row should not be written to output file.
using (StreamWriter file = new StreamWriter(filepathop)) {
for (int i = 0; i < csv.Length; i++) {
{
if (i == 0) {
file.WriteLine(header + "," + "num" + "," + "serial" + "," + "date");
}
else {
var newline = new StringBuilder();
string[] words = csv[i].Split(',');
string[] no = words[1].Split('/');
string number = no[0];
string serial = no[1];
newline.Append(number + "," + serial + "," + tokens[0]);
file.WriteLine(csv[i] + "," + newline);
}
}
}
}
}
}
}
You can test for null columns with string.IsNullOrEmpty(column) or column.Length == 0 like so:
if (!string.IsNullOrEmpty(serial) && !string.IsNullOrEmpty(country))
file.WriteLine(csv[i] + "," + newline);
You might want to check and remove white space, too. Depends on your input.

Reading style names in table cell of doc file in Apache-POI

I am able to read the table cells, But I wanted also to read the applied style name of each cell of a row in a table. How can I achieve this?
EDIT
Following is the code snip which I have tried. By this I am able to read cell text also the applied pstyle(para style), but not able to read the rstyles.
private static void processDoc(String path) throws Exception {
POIFSFileSystem fis = new POIFSFileSystem(new FileInputStream(path));
HWPFDocument wdDoc = new HWPFDocument(fis);
// list all style names and indexes in stylesheet
/*for (int j = 0; j < wdDoc.getStyleSheet().numStyles(); j++) {
if (wdDoc.getStyleSheet().getStyleDescription(j) != null) {
System.out.println(j + ": " + wdDoc.getStyleSheet().getStyleDescription(j).getName());
} else {
// getStyleDescription returned null
System.out.println(j + ": " + null);
}
}*/
// set range for entire document
Range range = wdDoc.getRange();
for (int i = 0; i < range.numParagraphs(); i++) {
Paragraph p = range.getParagraph(i);
// check if style index is greater than total number of styles
if (wdDoc.getStyleSheet().numStyles() > p.getStyleIndex()) {
//System.out.println(wdDoc.getStyleSheet().numStyles() + " -> " + p.getStyleIndex());
StyleDescription style = wdDoc.getStyleSheet().getStyleDescription(p.getStyleIndex());
String styleName = style.getName();
// write style name and associated text
System.out.println(styleName + " -> " + p.text().replaceAll("[\u0000-\u001f]", ""));
} else {
System.out.println("\n" + wdDoc.getStyleSheet().numStyles() + " ----> " + p.getStyleIndex());
}
}
}

FTSearch involving date fields is confusing me

I have Custom Control with a search screen that lets the users select any of up to six different fields to search on. I had no trouble getting all the other fields working with the exception of the two date fields. They can fill in both begin and end dates or just one or the other. Pretty standard stuff but I cannot figure out how to write the code to make the query work and have it do the search when it involves dates.
var tmpArray = new Array("");
var cTerms = 0;
if(requestScope.cmbSendTo != null & requestScope.cmbSendTo != "") {
a = #Right(requestScope.cmbSendTo, "(");
b = #Left(a,3);
tmpArray[cTerms++] = "(FIELD Mnemonic = \"" + b + "\")";
}
if(requestScope.edtFrom != & requestScope.edtFrom != "") {
tmpArray[cTerms++] = "(FIELD From = \"" + requestScope.edtFrom + "\")";
}
//**************************************************************************
if(requestScope.edtDateRangeFrom != null & requestScope.edtDateRangeFrom != "") {
tmpArray[cTerms++] = "(FIELD DeliveredDate >= \"" + requestScope.edtDateRangeFrom + "\")";
}
if(requestScope.edtDateRangeTo != null & requestScope.edtDateRangeTo != "") {
tmpArray[cTerms++] = "(FIELD DeliveredDate <= \"" + requestScope.edtDateRangeTo + "\")";
}
//**************************************************************************
if(requestScope.edtOriginal != null & requestScope.edtOriginal != "") {
tmpArray[cTerms++] = "(FIELD SourceFilename = \"" + requestScope.edtOriginal + "\")";
}
if(requestScope.edtCaptiva != null & requestScope.edtCaptiva != "") {
tmpArray[cTerms++] = "(FIELD Filename = \"" + requestScope.edtCaptiva + "\")";
}
qstring = tmpArray.join(" AND ").trim();
requestScope.queryString = qstring;
return qstring
Any assistance would be appreciated
The idea behind this screen was taken from this video:
XPages View Control - Add Full Text Search - http://www-10.lotus.com/ldd/ddwiki.nsf/dx/XPagesViewControlAddFullTextSearch.htm
The line if(requestScope.edtFrom != & requestScope.edtFrom != "") { is not complete. You miss the part to test for. I assume it lacks the null check and therefore should be:
if(requestScope.edtFrom != null & requestScope.edtFrom != "") {
Furthermore, you need to format the date to return what you expect for the query (e.g. MM/dd/yyyy). The formatting in the inputText control only applies to the visual formatting and not the format of the actual content.
Finally, you need to remove the quotes around the date.
The following code example based on your code will return the date without formatting and then return the date with the correct formatting:
<xp:button value="Label" id="button1">
<xp:eventHandler event="onclick" submit="true" refreshMode="partial" refreshId="computedField1"></xp:eventHandler>
</xp:button>
<xp:inputText id="edtDateRangeFrom" value="#{requestScope.edtDateRangeFrom}">
<xp:this.converter>
<xp:convertDateTime type="date"></xp:convertDateTime>
</xp:this.converter>
<xp:dateTimeHelper></xp:dateTimeHelper>
</xp:inputText>
<xp:text escape="true" id="computedField1">
<xp:this.value><![CDATA[#{javascript:var tmpArray = new Array("");
var cTerms = 0;
if(requestScope.edtDateRangeFrom != null & requestScope.edtDateRangeFrom != "") {
tmpArray[cTerms++] = "(FIELD DeliveredDate >= \"" + requestScope.edtDateRangeFrom + "\")";
var dateFormatter = new java.text.SimpleDateFormat( "MM/dd/yyyy" );
var formattedDate = dateFormatter.format( requestScope.edtDateRangeFrom );
tmpArray[cTerms++] = "(FIELD DeliveredDate >= " + formattedDate + ")";
}
qstring = tmpArray.join(" AND ").trim();
requestScope.queryString = qstring;
return qstring}]]>
</xp:this.value>
</xp:text>
It will return the following where the 2nd part is the format you are looking for:
(FIELD DeliveredDate >= "Fri Apr 27 12:00:00 CEST 2012")
AND (FIELD DeliveredDate >= 04/27/2012)
Here is your code with all these updates:
var tmpArray = new Array("");
var cTerms = 0;
var dateFormatter = new java.text.SimpleDateFormat( "MM/dd/yyyy" );
var formattedDate = "";
if(requestScope.cmbSendTo != null & requestScope.cmbSendTo != "") {
a = #Right(requestScope.cmbSendTo, "(");
b = #Left(a,3);
tmpArray[cTerms++] = "(FIELD Mnemonic = \"" + b + "\")";
}
if(requestScope.edtFrom != null & requestScope.edtFrom != "") {
tmpArray[cTerms++] = "(FIELD From = \"" + requestScope.edtFrom + "\")";
}
if(requestScope.edtDateRangeFrom != null & requestScope.edtDateRangeFrom != "") {
formattedDate = dateFormatter.format( requestScope.edtDateRangeFrom );
tmpArray[cTerms++] = "(FIELD DeliveredDate >= " + formattedDate + ")";
}
if(requestScope.edtDateRangeTo != null & requestScope.edtDateRangeTo != "") {
formattedDate = dateFormatter.format( requestScope.edtDateRangeTo );
tmpArray[cTerms++] = "(FIELD DeliveredDate <= " + formattedDate + ")";
}
if(requestScope.edtOriginal != null & requestScope.edtOriginal != "") {
tmpArray[cTerms++] = "(FIELD SourceFilename = \"" + requestScope.edtOriginal + "\")";
}
if(requestScope.edtCaptiva != null & requestScope.edtCaptiva != "") {
tmpArray[cTerms++] = "(FIELD Filename = \"" + requestScope.edtCaptiva + "\")";
}
qstring = tmpArray.join(" AND ").trim();
requestScope.queryString = qstring; // this just displays the query
return qstring // this is what sets the search property
If I'm reading it right, your query is resolving to
FIELD DeliveredDate >= "xx/yy/zz"
My first instinct was that you needed this instead:
FIELD DeliveredDate >= [xx/yy/zz]
But documentation indicates that you don't need brackets or quotes, so this:
FIELD DeliveredDate >= xx/yy/zz
Double check the query being created here. Perhaps print it to the screen or grab it from the debugger. You may see a problem there within the query and I believe you should be able to take that exact query and paste it in the search window of the database that has been full text indexed.
Also, have a look at this doc which covers notes query syntax, it may help you troubleshoot. I didn't see anything wrong in your code though.
http://www.loganmachinists.com/help/help8_client.nsf/f4b82fbb75e942a6852566ac0037f284/0e044d2c0639c979852572fe00687f29?OpenDocument
dates should always ( in my experience ) be written in the format mm/dd/yyyy so for instance
[deliverdatemin] >= 1/1/2012 and [deliverdatemax] <= 1/30/2012
An easy way to find out which query you are generating is to use the following piece of code to throw an error with the query generated
//youre own code
throw new java.lang.exception(queryvariable);
Or you could simply do a print() to display the query on the serverconsole
As of my concern The best way to handle the date field is that converting our date value for one specific format using NotesDateTime., Because this is the best date conversion for xpage.
Dim dateTime As New NotesDateTime( "date String" )
or
Dim dateTime As New NotesDateTime( NotedateTime.getDtaeOnly() )

Resources