最近纠结于读取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数据库中,经测试,可行,附上代码,仅供参考!

附:Excel导入SQLserver示例下载

Silverlight将Excel导入到SQLserver数据库的更多相关文章

  1. Excel 数据导入至Sqlserver 数据库中 ltrim() 、rtrim() 、replace() 函数 依次空格无效问题

    今天导一些数据从Excel中至Sqlserver 数据库中,在做数据合并去重的时候发现,有两条数据一模一样,竟然没有进行合并: 最后发现有一条后面有个“空格”,正是因为这个“空格”让我抓狂许久,因为它 ...

  2. 使用PhpSpreadsheet将Excel导入到MySQL数据库

    本文以导入学生成绩表为例,给大家讲解使用PhpSpreadsheet将Excel导入的MySQL数据库. 准备 首先我们需要准备一张MySQL表,表名t_student,表结构如下: CREATE T ...

  3. EXCEL批量导入到Sqlserver数据库并进行两表间数据的批量修改

    Excel 大量数据导入到sqlserver生成临时表并将临时表某字段的数据批量更新的原表中的某个字段 1:首先要对EXCEL进行处理 列名改成英文,不要有多余的列和行(通过ctrl+shift 左或 ...

  4. c# excel如何导入到sqlserver数据库

    最近在做这个如何把excel导入到数据库中,经过多方查找,终于找到一个适合的,并且经过自己的完善可以正常使用(忘记原作者博客的链接地址了,敬请见谅) 首先是窗体的创建,文本框显示文件的路径,按钮执行操 ...

  5. Npoi将excel数据导入到sqlserver数据库

    /// <summary> /// 将excel导入到datatable /// </summary> /// <param name="filePath&qu ...

  6. ASP.NET Excel导入Sql Server数据库(转)

    先看界面图 实现的基本思想: 1,先使用FileUpload控件fuload将Excel文件上传到服务器上得某一个文件夹. 2,使用OleDb将已经上传到服务器上的Excel文件读出来,这里将Exce ...

  7. Excel表格数据导入到SQLServer数据库

    转载:http://blog.csdn.net/lishuangzhe7047/article/details/8797416 步骤: 1,选择要插入的数据库--右键--任务--导入数据 2,点击下一 ...

  8. 将Excel文件数据导入到SqlServer数据库的三种方案

    方案一: 通过OleDB方式获取Excel文件的数据,然后通过DataSet中转到SQL Server,这种方法的优点是非常的灵活,可以对Excel表中的各个单元格进行用户所需的操作. openFil ...

  9. 使用navicat for sqlserver 把excel中的数据导入到sqlserver数据库

    以前记得使用excel向mysql中导入过数据,今天使用excel向sqlserver2005导入了数据,在此把做法记录一下 第一步:准备excel数据,在这个excel中有3个sheet,每个she ...

随机推荐

  1. 1019 Least Common Multiple

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submission( ...

  2. Modelsim使用笔记(一个完成工程的仿真)

    这学期在玩Altera的板子,不不, 现在应该叫intel PSG.在QuartusII13.0上老喜欢用modelsim_ae做仿真,小工程用起来也方便,但是我做IIC配置摄像头的时序仿真时,就显得 ...

  3. 画地为Mask,随心所欲的高效遮罩组件[Unity]

    在上一篇博文"扔掉遮罩,更好的圆形Image组件"中,笔者改变Image的顶点数据,使得Image呈圆形显示,避免了Mask的使用,从而节省Drawcall消耗,提高渲染效率了.这 ...

  4. cd命令使用详解

    cd命令是目录切换命令,是shell内置命令. 语法: cd [-L|-P] [dir] 选项: -p 如果要切换到的目标目录是一个符号连接,直接切换到符号连接指向的目标目录 -L 如果要切换的目标目 ...

  5. Python冒泡算法和修改配置文件

    先学习之前未完成的冒泡算法 li = [13,22,6,99,11] 从小到大 从第一个数字比较把大的往后移位 for m in range(4): num1 = li[m] num2 = li[m+ ...

  6. 学生成绩管理C语言版

    [标题]学生成绩管理的设计与实现 [开发语言]C语言 [概要设计]使用结构体存储学生的学号.姓名和成绩信息,实现对学生成绩类的基本操作:增加.删除.查询.排序 [测试数据]按提示输入5组正确的正确的数 ...

  7. URI结构

    [scheme:][//host:port][path][?query][#fragment] path:从端口后第一个/开始,可以有多个,每个用/连接. query:从第一个?开始,至行尾或#结束. ...

  8. html学习笔记 - sublime text 插件安装

    command + shift + p 呼出搜索界面 输入 Packge Control:Install Package 进入到插件搜索列表 Emmet -- >快速生成html标签结构 Emm ...

  9. Swift 入门之简单语法(三)

    集合 数组 数组使用 [] 定义,这一点与 OC 相同 //: [Int] let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 遍历 for num in nu ...

  10. 利刃 MVVMLight

    已经很久没有写系列文章了,上一次是2012年写的HTLM5系列,想想我们应该是较早一批使用HTML5做项目的人. 相比我当时动不动100+的粉丝增长和两天3000+的阅读量,MVVM Light只能算 ...