unlocking excel file exported from javaFX Desktop App - file

I looked at this post
I know this post is old,I'm having the same issue with excel file. My scenario is: I have a Desktop app written in javaFX the user export a TableView content into an excel file. Everything goes fine except when the file tries to open the message of the file is locked by user for editing.
How do I force or work around to unlock the file from the App that generate it?
This was my initial code
String directory = CreateDir();
if (rs != null) {
File file_excel = new File(directory + "\\" + reportName + ".xls");
file_excel.createNewFile();
while (rs.next()) {
pc.exportToXls_File(sql, uID, uPW, file_excel);
}
Desktop.getDesktop().open(file_excel);
}
exportToXls_File Function
public void exportToXls_File(String sql, String userName, String passWord, File fileName)
throws SQLException, FileNotFoundException, IOException, Exception {
ActionEvent event = new ActionEvent();
DBConnection dbc = new DBConnection();
conn = dbc.getConnection(event, userName, passWord);
try {
try (
/**
* Create new Excel workbook and sheet
*/
HSSFWorkbook xlsWorkbook = new HSSFWorkbook()) {
HSSFSheet xlsSheet = xlsWorkbook.createSheet();
short rowIndex = 0;
/**
* Execute SQL query
*/
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
/**
* Get the list of column names and store them as the first Row
* of the spreadsheet.
*/
ResultSetMetaData colInfo = rs.getMetaData();
List<String> colNames = new ArrayList<>();
HSSFRow titleRow = xlsSheet.createRow(rowIndex++);
for (int i = 1; i <= colInfo.getColumnCount(); i++) {
colNames.add(colInfo.getColumnName(i));
titleRow.createCell((int) (i - 1)).setCellValue(
new HSSFRichTextString(colInfo.getColumnName(i)));
xlsSheet.setColumnWidth((int) (i - 1), (short) 4000);
}
/**
* Save all the data from the database table rows
*/
while (rs.next()) {
HSSFRow dataRow = xlsSheet.createRow(rowIndex++);
int colIndex = 0;
for (String colName : colNames) {
dataRow.createCell(colIndex++).setCellValue(
new HSSFRichTextString(rs.getString(colName)));
}
}
/**
* Write to disk
*/
xlsWorkbook.write(new FileOutputStream(fileName));
xlsWorkbook.close();
}
} catch (IOException | SQLException ex) {
out.println(ex);
} finally {
if (conn != null) {
stmt.close();
closeConnection((OracleConnection) conn);
conn.close();
}
}
}
Thank you

Related

Syntax error at or near ( error - error code 42601

I am migrating a c# application from sql server express edition to postgresql using npgsql 4.1.3.1. However I am getting the syntax error 42601 whenever i try to add row a databound datagridview programmatically. I had a look at the update command generated by npgsqlcommandbuilder and it includes an extra parenthesis at the end. ("pfuppersalarylimit" = #p133)) of the command. Any help shall be highly appreciated.
`NpgsqlConnection con;`
NpgsqlCommand sqlcmd;
NpgsqlCommandBuilder builder;
DataSet ds;
BindingSource bs = new BindingSource();
public frmEmployee()
{
string str = Properties.Settings.Default.connectionstring; //.Settings.connectionstring2;
con = new Npgsql.NpgsqlConnection(str); //
InitializeComponent();
}
private void frmEmployee_Load(object sender, EventArgs e)
{
string sql = "Select * from employee where company_code='S00159' order by rownumber";
ds = new DataSet();
da = new NpgsqlDataAdapter(sql, con);
builder = new NpgsqlCommandBuilder(da);
da.Fill(ds);
bs.DataSource = ds;
bs.DataMember = ds.Tables[0].ToString();
DataGridView1.DataSource = bs;
}
private void addemployee_Click(object sender, EventArgs e)
{
int start_row_number;
int pos1;
try
{
if (DataGridView1.Rows.Count == 0)
{
pos1 = 0;
start_row_number = 1; // added on 15/10/2011
}
else
{
pos1 = DataGridView1.CurrentCell.RowIndex + 1;
start_row_number = Convert.ToInt32(DataGridView1.Rows[pos1 - 1].Cells["rownumber"].Value) + 1;
}
DataRow employeeRow = ds.Tables[0].NewRow();
string emplcode = companyInfo.company_code.Substring(1, 1) + classMisc.genEmployeeCodeNew(); // just a random number
employeeRow["company_code"] = companyInfo.company_code.Trim();
employeeRow["employee_code_no"] = emplcode;
employeeRow["srno"] = classMisc.getsrno();
employeeRow["flag"] = true;
employeeRow["rownumber"] = start_row_number; // pos1
employeeRow["mobile"] = 0;
employeeRow["aadhar"] = 0;
employeeRow["pfuppersalarylimit"] = 0;
ds.Tables[0].Rows.InsertAt(employeeRow, pos1);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "error 1");
}
}

Implementing safe areas with Infinite Container pull to refresh

How can I set the safe area for pull to refresh? I have a form with with an infinite container. I set the IC with safe area ic.setSafeArea(true). When I rotate the screen the safe area is respected(see image 1). If i pull to refresh the safe area is not respected (see image 2). With the below code taken from the InfiniteContainerSample, how can I ensure the safe area is respected after pull to refresh?
image 1
public void showForm() {
Form hi = new Form("InfiniteContainer", new BorderLayout());
Style s = UIManager.getInstance().getComponentStyle("MultiLine1");
FontImage p = FontImage.createMaterial(FontImage.MATERIAL_PORTRAIT, s);
EncodedImage placeholder = EncodedImage.createFromImage(p.scaled(p.getWidth() * 3, p.getHeight() * 3), false);
InfiniteContainer ic = new InfiniteContainer() {
#Override
public Component[] fetchComponents(int index, int amount) {
java.util.List<Map<String, Object>> data = fetchPropertyData("Leeds");
MultiButton[] cmps = new MultiButton[data.size()];
for(int iter = 0 ; iter < cmps.length ; iter++) {
Map<String, Object> currentListing = data.get(iter);
if(currentListing == null) {
return null;
}
String thumb_url = (String)currentListing.get("thumb_url");
String guid = (String)currentListing.get("guid");
String summary = (String)currentListing.get("summary");
cmps[iter] = new MultiButton(summary);
cmps[iter].setIcon(URLImage.createToStorage(placeholder, guid, thumb_url));
}
return cmps;
}
};
ic.setUIID("Blue");
ic.setSafeArea(true);
ic.addComponent(new Label("This is a test"));
hi.add(BorderLayout.CENTER, ic);
hi.show();
}
int pageNumber = 1;
java.util.List<Map<String, Object>> fetchPropertyData(String text) {
try {
ConnectionRequest r = new ConnectionRequest();
r.setPost(false);
r.setUrl("http://api.nestoria.co.uk/api");
r.addArgument("pretty", "0");
r.addArgument("action", "search_listings");
r.addArgument("encoding", "json");
r.addArgument("listing_type", "buy");
r.addArgument("page", "" + pageNumber);
pageNumber++;
r.addArgument("country", "uk");
r.addArgument("place_name", text);
NetworkManager.getInstance().addToQueueAndWait(r);
Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
Map<String, Object> response = (Map<String, Object>)result.get("response");
return (java.util.List<Map<String, Object>>)response.get("listings");
} catch(Exception err) {
Log.e(err);
return null;
}
}
Thanks for reporting this. This has been fixed on github. It will be included in the next release on Friday.

Query does not return all data from database

I have a C# 4.0 WinForms App using SQL Server 2012 database.
On one of my forms, I select a range of dates from a MonthCalendar.
In a query using a SqlDataAdapter, the query should return 4-names of people from a table.
After filling the DataTable, the "for" loop successfully pulls the first name.
On the next iteration, it also pulls the 2nd person's name from the table.
However, on the 3rd iteration, it again pulls the 2nd person's name and does not retrieve the remaining 2-names.
Using SSMS, I can see all 4-names of the people I'm querying. If I use the query below in SSMS, I again get all 4-names.
Does anyone have an idea why the code below fails to return all 4-names, but returns a previous name?
Here is the code I'm using to query the SQL Server database.
private string ReturnPerson(string dStart, string dEnd)
{
string myPerson = "";
try
{
using (SqlConnection conn = new SqlConnection(#"..."))
{
conn.Open();
using (SqlDataAdapter adap = new SqlDataAdapter("SELECT person, scheduledDate FROM Assignments WHERE scheduledDate BETWEEN #start AND #end ORDER BY scheduledDate ASC", conn))
{
adap.SelectCommand.Parameters.Add("#start", SqlDbType.NVarChar).Value = dStart;
adap.SelectCommand.Parameters.Add("#end", SqlDbType.NVarChar).Value = dEnd;
using (DataTable dt = new DataTable())
{
adap.Fill(dt);
for (int i = 0; i < dt.Rows.Count - 1; i++)
{
DataRow row = dt.Rows[i];
DataRow nextRow = dt.Rows[i + 1];
if (personRowCounter == 0)//rowCounter declared globaly
{
myPerson = row.Field<string>("person").ToString();
personRowCounter++;
return myPerson;
}
else if (personRowCounter > 0)
{
myPerson = nextRow.Field<string>("person").ToString();
personRowCounter++;
return myPerson;
}
}
}
}
}
}
catch (SqlException ex) { MessageBox.Show(ex.Message); }
catch (System.Exception ex) { MessageBox.Show(ex.Message); }
return myPerson;
}
If you start with personRowCounter =0
Then the first call will return row 0 as personRowCounter = 0 and i = 0 and it will set personRowCounter = 1
Then the next call will return row 1 as personRowCounter > 0 and i= 0 and it will set personRowCounter = 1
And all calls after that will return row 1 as personRowCounter > 0 and the loop always starts from 0
I'm not sure what you're intent is here. But, I believe that the problem lies with
DataRow nextRow = dt.Rows[i + 1];
That will throw an exception when i is pointing to the last row. Because [i + 1] will index beyond the end of dt.rows.
Based on the comments above, I've figured out the solution. I needed to adjust the DataRow rows, as per below. This allowed me to pull in the remaining data.
private string ReturnPerson(string dStart, string dEnd)
{
string myPerson = "";
try
{
using (SqlConnection conn = new SqlConnection(#"..."))
conn.Open();
using (SqlDataAdapter adap = new SqlDataAdapter("SELECT person, scheduledDate FROM Assignments WHERE scheduledDate BETWEEN #start AND #end ORDER BY scheduledDate ASC", conn))
{
adap.SelectCommand.Parameters.Add("#start", SqlDbType.NVarChar).Value = dStart;
adap.SelectCommand.Parameters.Add("#end", SqlDbType.NVarChar).Value = dEnd;
using (DataTable dt = new DataTable())
{
adap.Fill(dt);
for (int i = 0; i < dt.Rows.Count - 1; i++)
{
DataRow row0 = dt.Rows[i];
DataRow row1 = dt.Rows[i + 1];
DataRow row2 = dt.Rows[i + 2];
DataRow row3 = dt.Rows[i + 3];
if (dt.Rows.Count > 4)
{
DataRow row4 = dt.Rows[4];
}
if (personRowCounter == 0)//rowCounter declared globaly
{
myPerson = row0.Field<string>("person").ToString();
personRowCounter++;
return myPerson;
}
else if (personRowCounter == 1)
{
myPerson = row1.Field<string>("person").ToString();
personRowCounter++;
return myPerson;
}
else if (personRowCounter == 2)
{
myPerson = row2.Field<string>("person").ToString();
personRowCounter++;
return myPerson;
"etc.";
}
}
}
}
}
catch (SqlException ex) { MessageBox.Show(ex.Message); }
catch (System.Exception ex) { MessageBox.Show(ex.Message); }
return myPerson;
}

How to display column headers in the Exported Excel

I am following a tutorial "Export data from sql server database to excel in wpf". Now I can achieve the function successfully. But in the exported Excel file, there is no column names (database column headers like CustomerId, CustomerName, city, postcode, telephoneNo...)
.
How can I get this feature? Also, how can I open a SaveAs dialogue? Thanks. The following is my code:
private void button1_Click(object sender, RoutedEventArgs e)
{
string sql = null;
string data = null;
int i = 0;
int j = 0;
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = #"Data Source=.\sqlexpress;Initial Catalog=Client;Integrated Security=SSPI;";
cnn.Open();
sql = "select * from Customers";
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
DataSet ds = new DataSet();
dscmd.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
{
data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 1, j + 1] = data;
}
}
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
I'm not an expert in this, but I believe that you can use an underscore character (_) in a Range object to select or edit a column header:
xlWorkSheet.Range["A1", _].Value2 = "Heading for first column";

database in Jtable and add jcheckbox in last column of all rows

since I am beginner, Jtable concept has made my brain rack a lot. with difficult i have maganaged to read a database and add it to jtable CODE given below. but am stuck as how to ADD A JCHECKBOX IN THE LAST COLUMN OF THE SAME TABLE.
public class ttt extends JFrame{
ResultSet rs;
int colcount;
String[] headers;
Connection con;
Statement st;
ttt(){
final Vector columnNames = new Vector();
final Vector data = new Vector();
JPanel panel=new JPanel();
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Driver loaded");
// Establish a connection
con= DriverManager.getConnection
("jdbc:odbc:ysr");
System.out.println("Database connecteddddd");
// Create a statement
st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT
Block_Name,Panchayat_Name,Village_Name," +
" Habitation_Name,Scheme_Name,Sanction_Amount FROM
ysr2011 where Habitation_Name= '10th mile' ");
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement( md.getColumnName(i) );
}
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
}
catch(Exception e){}
JTable table = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
panel.add(scrollPane);
add(panel);
}
public static void main(String arg[])
{
try
{
ttt frame=new ttt();
frame.setSize(550,200);
frame.setVisible(true);
}
catch(Exception e)
{}
}
}
ANY HELP IS REALLY A WELCOME GESTURE. THANKING IN ADVANCE.
You would add the check box here:
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement( md.getColumnName(i) );
}
columnNames.addElement("Check Box");
while (rs.next()) {
Vector row = new Vector(columns + 1);
for (int i = 1; i <= columns; i++) {
row.addElement( rs.getObject(i) );
}
row.addElement(new JCheckBox());
data.addElement( row );
}
Use your own column title. You're also going to have to define the check boxes more completely because eventually you're going to add tests for the isSelected method.

Resources