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";
Related
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");
}
}
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;
}
Im trying to update rows in my table using loop, I get no error but nothing changed in my data...Thats my code.. What am I missing ?
private void updateZipInDB(List<ZipObj> zipCodeToUpdate)
{
var comm = "";
string DbConnString = ConfigurationManager.AppSettings["dbConnectionString"].ToString();
using (SqlConnection conn = new SqlConnection(DbConnString))
{
comm = "UPDATE Account SET address1_postalcode = #newVal WHERE AccountId = #accountID";
using (SqlCommand command = new SqlCommand(comm, conn))
{
conn.Open();
command.Parameters.AddWithValue("#newVal", "f");
command.Parameters.AddWithValue("#accountID", "f");
for (int i = 0; i < zipCodeToUpdate.Count; i++)
{
zipCodeToUpdate[i].NewVal + "' WHERE AccountId = '" + zipCodeToUpdate[i].AccountId + "'";
command.Parameters["#newVal"].Value = zipCodeToUpdate[i].NewVal;
command.Parameters["#accountID"].Value = zipCodeToUpdate[i].AccountId;
command.ExecuteNonQuery();
}
conn.Close();
}
}
}
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
I tried to insert excel data to database, MS SQL.
Currently I looped the excel records and insert. It took too long.
Is there any way to insert excel records to database once ?
Thanks and Regards,
Here is my code:
User user = new User();
cmd_obj = new OleDbCommand("SELECT * FROM [Sheet1$]", con_obj);
OleDbDataReader dr = cmd_obj.ExecuteReader();
while (dr.Read())
{
int blnBadSyntax = 0;
int blnBadDomain = 0;
int blnBadSMTP = 0;
int blnGreylisted = 0;
int blnBadMailbox = 0;
bool blnIsValid = false;
string key = "2CH3W-7ENLC-FWLZ4-WEUVY-JRQ11-AU69U-W63V5-ULF1C-DA5RC-RU7XS-XK6JY-6JT5U-MYLX";
MXValidate.LoadLicenseKey(key);
MXValidate mx = new MXValidate();
mx.LogInMemory = true;
mx.CheckLiteralDomain = true;
mx.CheckGreylisting = true;
try
{
MXValidateLevel level = mx.Validate(user.StrEmailId, MXValidateLevel.Mailbox);
switch (level)
{
case MXValidateLevel.NotValid:
blnBadSyntax = 1;
break;
case MXValidateLevel.Syntax:
blnBadDomain = 1;
break;
case MXValidateLevel.MXRecords:
blnBadSMTP = 1;
break;
case MXValidateLevel.SMTP:
blnGreylisted = 1;
blnIsValid = true;
break;
case MXValidateLevel.Greylisted:
blnBadMailbox = 1;
blnIsValid = true;
break;
case MXValidateLevel.Mailbox:
blnIsValid = true;
break;
}
user.BlnBadSyntax = blnBadSyntax;
user.BlnBadDomain = blnBadDomain;
user.BlnBadSMTP = blnBadSMTP;
user.BlnGraylisted = blnGreylisted;
user.BlnBadMailBox = blnBadMailbox;
if (blnIsValid)
{
user.StrStatus = "Valid";
}
else
{
user.StrStatus = "InValid";
logFile.writeLog(mx.GetLog());
}
}
catch (DnsException ex)
{
logFile.writeLog(mx.GetLog());
}
InsertuserDetails(user);
}
You can do this with the help of SqlBulkCopy if the data is large.
Kindly check the following post for more details:
http://technico.qnownow.com/bulk-copy-data-from-excel-to-destination-db-using-sql-bulk-copy/
// Connection String to Excel Workbook
string excelConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Book1.xls;ExtendedProperties=""Excel 8.0;HDR=YES;""";
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select ID,Data FROM [Data$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=.;Initial Catalog=Test;Integrated Security=True";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelData";
bulkCopy.WriteToServer(dr);
}