currently I have a web which loads excel spreadsheet data into SQL database. When the page loads, all the parameters are hard coded on the code behind, so I do not have ‘browse for file’ and ‘upload’ button. I would like to implement these 2 buttons but I am not sure how should I do it.
I am using C# language, Visual Studio 2005 and SQL Server 2005.
Below is the code which runs the import of excel data into the database:
importexcel.aspx.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Data.OleDb;
using System.Data.Common;
using System.Data.SqlClient;
public partial class ImportExcel : System.Web.UI.Page
{
public static string path = @"c:\Documents and Settings\rhlim\My Documents\Visual Studio 2005\WebSites\insqlserver\studentsheet1.xls";
public static string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=Excel 8.0;";
protected void Page_Load(object sender, EventArgs e)
{
// Create Connection to Excel Workbook
using (OleDbConnection connection =
new OleDbConnection(connStr))
{
OleDbCommand command = new OleDbCommand
("Select StudentName,RollNo,Course FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=<IP>;Initial Catalog=<database>;User ID=<userid>;Password=<password>";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "tStudent";
bulkCopy.WriteToServer(dr);
}
}
}
}
}
Below is my code for the my current html:
importexcel.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ImportExcel.aspx.cs" Inherits="ImportExcel" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title></title>
<script language="javascript" type="text/javascript">
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
Please select a Excel spreadsheet to import:<br />
<asp:FileUpload ID="fupExcel" runat="server" />
<br />
<br />
<asp:Button ID="btnImport" runat="server"
Text="Import" onclick="btnImport_Click" />
<br />
<br />
<a href=http://localhost:1701/SoD>Click to go to main page</a>
</form>
</body>
</html>
I am not sure how do I attach the 2 buttons to my background code, someone teach me? Best if with sample code, thanks a lot!
First, the code in your page load needs to execute only
if(IsPostBack)or on button click.Second, (At leas modern) browsers won’t let you change the value of the input file field, or click it.
You might try with some flash upload thing or so, but I don’t expect much.