Silverlight将Excel导入到SQLserver数据库
最近纠结于读取Excel模板数据,将数据导入SQLServer的Silverlight实现,本文将实现代码贴出,作为一个简单的例子,方便各位:
1.先设计前台界面新建Silverlight5.0应用程序,出现MainPage.xaml,代码如下所示:
<UserControl x:Class="Excel导入SQLServer数据库.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Width="" Height=""> <Grid x:Name="LayoutRoot" Background="White">
<ListBox Name="listBox1" HorizontalAlignment="Right" VerticalAlignment="Center" Width="" Height="" Margin="0,9,11,47">
</ListBox>
<Button x:Name="UploadButton" Content="确认上传" Click="UploadButton_Click" Width="" Height="" HorizontalAlignment="Right" Margin="0,37,12,18" />
<Button x:Name="OpenButton" Content="选择本地Excel文件" Click="OpenButton_Click" Width="" Height="" HorizontalAlignment="Right" Margin="0,8,258,47" />
</Grid>
</UserControl>
其效果图,如下所示:
其后台MainPage.xaml.cs代码,如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO; namespace Excel导入SQLServer数据库
{
public partial class MainPage : UserControl
{
//在此先定义一个List;
List<FileInfo> filesToUpload;
public MainPage()
{
InitializeComponent();
} /// <summary>
/// 确认上传
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void UploadButton_Click(object sender, RoutedEventArgs e)
{
try
{
if (filesToUpload == null)
{
return;
}
foreach (FileInfo file in filesToUpload)
{
//Define the Url object for the Handler
UriBuilder handlerUrl = new UriBuilder("http://localhost:5952/UploadFileHandler.ashx");//自己的端口
//Set the QueryString
handlerUrl.Query = "InputFile=" + file.Name;
FileStream FsInputFile = file.OpenRead();
//Define the WebClient for Uploading the Data
WebClient webClient = new WebClient();
//Now make an async class for writing the file to the server
//Here I am using Lambda Expression
webClient.OpenWriteCompleted += (s, evt) =>
{
UploadFileData(FsInputFile, evt.Result);
evt.Result.Close();
FsInputFile.Close();
MessageBox.Show("上传成功!");
listBox1.ItemsSource = ""; };
webClient.OpenWriteAsync(handlerUrl.Uri);
} }
catch (System.Exception)
{ throw;
}
} private void UploadFileData(Stream inputFile, Stream resultFile)
{
byte[] fileData = new byte[];
int fileDataToRead;
while ((fileDataToRead = inputFile.Read(fileData, , fileData.Length)) != )
{
resultFile.Write(fileData, , fileDataToRead);
}
} /// <summary>
/// 打开文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OpenButton_Click(object sender, RoutedEventArgs e)
{
try
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Multiselect = false;
//这里只写了Excel有关格式,可以根据需要添加其他格式
fileDialog.Filter = "Excel Files(*.xls,*.xlsx)|*.xls";
bool? result = fileDialog.ShowDialog();
if (result != null)
{
if (result == true)
{
filesToUpload = fileDialog.Files.ToList();
listBox1.ItemsSource = filesToUpload;
}
else
return;
}
}
catch (System.Exception)
{ throw;
}
}
}
}
注意:将其中的端口号跟自己的程序相对应,如下图:
接着,在.web目录下,新建FilesServer文件夹,和UploadFileHandler.ashx的一般处理程序,如下图:
其中,UploadFileHandler.ashx.cs中内容如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.OleDb;
using System.Data;
using System.Data.SqlClient;
using System.IO; namespace Excel导入SQLServer数据库.Web
{
/// <summary>
/// UploadFileHandler 的摘要说明
/// </summary>
public class UploadFileHandler : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
try
{
string filename = context.Request.QueryString["InputFile"].ToString();
using (FileStream fileStream = File.Create(context.Server.MapPath("~/FilesServer/" + filename)))
{
byte[] bufferData = new byte[];
int bytesToBeRead;
while ((bytesToBeRead = context.Request.InputStream.Read(bufferData, , bufferData.Length)) != )
{
fileStream.Write(bufferData, , bytesToBeRead);
}
fileStream.Close(); }
//===========用于对上传的EXCEL文件插入到SQL数据库中=============== string strPath = context.Server.MapPath("~/FilesServer/" + filename);
//string mystring = "Provider = Microsoft.Jet.OleDb.4.0 ; Data Source = '" + strPath + "';Extended Properties=Excel 8.0";//之前版本链接格式
string mystring = "Provider = Microsoft.ACE.OLEDB.12.0 ; Data Source = '" + strPath + "';Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";//office2010链接格式
OleDbConnection cnnxls = new OleDbConnection(mystring);
if (cnnxls.State == ConnectionState.Closed)
{
cnnxls.Open();
}
OleDbDataAdapter myDa = new OleDbDataAdapter("select * from [Sheet1$]", cnnxls);
DataSet myDs = new DataSet();
myDa.Fill(myDs);
string ConnStr = "Data Source=WIN-FKM3JDGK01I\\MYSQLR2;Initial Catalog=CDDB;Persist Security Info=True;User ID=sa;Password=123456";
SqlConnection MyConn = new SqlConnection(ConnStr);
MyConn.Open();
//读取Excel中的数据
string xuehao = myDs.Tables[].Rows[][].ToString();
string xingming = myDs.Tables[].Rows[][].ToString();
string strSQL = "insert into CDDB.dbo.Student(XUEHAO,NAME) values ('" + xuehao + "','" + xingming + "')";
SqlCommand myComm1 = new SqlCommand(strSQL, MyConn);
myComm1.ExecuteNonQuery();
MyConn.Close();
cnnxls.Close();
}
catch (Exception)
{ throw;
} } public bool IsReusable
{
get
{
return false;
}
}
}
}
注意事项,参考下图:
如此,可以将Excel中的数据写入SQLserver数据库中,经测试,可行,附上代码,仅供参考!
Silverlight将Excel导入到SQLserver数据库的更多相关文章
- Excel 数据导入至Sqlserver 数据库中 ltrim() 、rtrim() 、replace() 函数 依次空格无效问题
今天导一些数据从Excel中至Sqlserver 数据库中,在做数据合并去重的时候发现,有两条数据一模一样,竟然没有进行合并: 最后发现有一条后面有个“空格”,正是因为这个“空格”让我抓狂许久,因为它 ...
- 使用PhpSpreadsheet将Excel导入到MySQL数据库
本文以导入学生成绩表为例,给大家讲解使用PhpSpreadsheet将Excel导入的MySQL数据库. 准备 首先我们需要准备一张MySQL表,表名t_student,表结构如下: CREATE T ...
- EXCEL批量导入到Sqlserver数据库并进行两表间数据的批量修改
Excel 大量数据导入到sqlserver生成临时表并将临时表某字段的数据批量更新的原表中的某个字段 1:首先要对EXCEL进行处理 列名改成英文,不要有多余的列和行(通过ctrl+shift 左或 ...
- c# excel如何导入到sqlserver数据库
最近在做这个如何把excel导入到数据库中,经过多方查找,终于找到一个适合的,并且经过自己的完善可以正常使用(忘记原作者博客的链接地址了,敬请见谅) 首先是窗体的创建,文本框显示文件的路径,按钮执行操 ...
- Npoi将excel数据导入到sqlserver数据库
/// <summary> /// 将excel导入到datatable /// </summary> /// <param name="filePath&qu ...
- ASP.NET Excel导入Sql Server数据库(转)
先看界面图 实现的基本思想: 1,先使用FileUpload控件fuload将Excel文件上传到服务器上得某一个文件夹. 2,使用OleDb将已经上传到服务器上的Excel文件读出来,这里将Exce ...
- Excel表格数据导入到SQLServer数据库
转载:http://blog.csdn.net/lishuangzhe7047/article/details/8797416 步骤: 1,选择要插入的数据库--右键--任务--导入数据 2,点击下一 ...
- 将Excel文件数据导入到SqlServer数据库的三种方案
方案一: 通过OleDB方式获取Excel文件的数据,然后通过DataSet中转到SQL Server,这种方法的优点是非常的灵活,可以对Excel表中的各个单元格进行用户所需的操作. openFil ...
- 使用navicat for sqlserver 把excel中的数据导入到sqlserver数据库
以前记得使用excel向mysql中导入过数据,今天使用excel向sqlserver2005导入了数据,在此把做法记录一下 第一步:准备excel数据,在这个excel中有3个sheet,每个she ...
随机推荐
- Spring Boot 整合 MyBatis
前言 现在业界比较流行的数据操作层框架 MyBatis,下面就讲解下 Springboot 如何整合 MyBatis,这里使用的是xml配置SQL而不是用注解.主要是 SQL 和业务代码应该隔离,方便 ...
- 像写C#一样编写java代码
JDK8提供了非常多的便捷用法和语法糖,其编码效率几乎接近于C#开发,maven则是java目前为止最赞的jar包管理和build工具,这两部分内容都不算多,就合并到一起了. 愿编写java代码的过程 ...
- Centos6.5静默安装Oracle11g
sed -i "s/SELINUX=enforcing/SELINUX=disabled/" /etc/selinux/configsetenforce 0yum -y insta ...
- Linux中Nginx反向代理下的tomcat集群
Nginx具有反向代理(注意和正向代码的区别)和负载均衡等特点. 这次Nginx安装在 192.168.1.108 这台linux 机器上.安装Nginx 先要装openssl库,gcc,PCRE,z ...
- Java学习笔记——I/O流
朝辞白帝彩云间,千里江陵一日还.两岸猿声啼不尽,轻舟已过万重山. --早发白帝城 我们老师写代码有个特点,就是简洁.每一句的意图都十分明确.所以他讲课的速度也比较快. 跑题了,说说I/O流: 1.字节 ...
- Sql Server + ADO.NET
MsSql-http://www.cnblogs.com/zhangwei595806165/archive/2012/02/23/2364746.html 协议:Shared Memory :效率最 ...
- VR的发展历程-VR全景智慧城市
从1962年有第一台VR开始,到2014年Oculus被Facebook收购为止,VR经历了一个非常漫长的过程.从鲜为人知,到被广泛认识,逐渐走进我们生活.这就是VR形成的时代.在这个时代里,VR设备 ...
- Azure Messaging-ServiceBus Messaging消息队列技术系列-索引篇
Azure Messaging ServiceBus Messaging相关的技术系列,最近已经整理了不少了,统一做一个索引链接,置顶. 方便查找,并后续陆陆续续再增加. 学习消息队列技术,可以先看第 ...
- java 线程方法join的简单总结
虽然关于讨论线程join方法的博客已经很多了,不过个人感觉挺多都讨论得不够全面,所以我觉得有必要对其进行一个全面的总结. 一.作用 Thread类中的join方法的主要作用就是同步,它可以使得线程之间 ...
- 基于Spring Boot的图片上传
package com.clou.inteface.domain.web.user; import java.io.File; import java.io.IOException; import j ...