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 ...
随机推荐
- sscanf( )函数初体验
解析字符串,将%格式的内容,存储到后面的参数中 %% - 返回一个百分号 % %c - ASCII 值对应的字符 %d - 包含正负号的十进制数(负数.0.正数) %e - 使用小写的科学计数法(例如 ...
- dotNet Linux 学习记录 - Jexus寄宿WCF服务
让WCF运行在Linux上(寄宿于服务器程序) WCF介绍请自行 bing 搜索 使用的开发工具为vs2017,系统为 Ubuntu16.04 服务器软件为Jexus ( 详情请看: Jexus官网 ...
- JAVA的HashSet源码分析
一.HashSet概述 HashSet实现Set接口,由哈希表(实际上是一个HashMap实例)支持.它不保证set的迭代顺序:特别是它不保证该顺序恒久不变.此类允许使用null元素. 二.HashS ...
- CompletionService 简介
以下是jdk关于CompletionService的简介: public interface CompletionService<V> 将生产新的异步任务与使用已完成任务的结果分离开来的服 ...
- 数组的重排序方法reverse()和sort()
js数组中存在两个可以直接用来重排序的方法:reverse()和sort(). reverse()方法比较简单,直接反转数组项的顺序: var arr = [1, 3, 2, 4, 5]; arr.r ...
- 4.从AbstractQueuedSynchronizer(AQS)说起(3)——AQS结语
前两节的内容<2.从AbstractQueuedSynchronizer(AQS)说起(1)——独占模式的锁获取与释放> .<3.从AbstractQueuedSynchronize ...
- 传感器系列之4.12GPS定位传感器
4.12 GPS定位实验 一.实验目的 了解GPS的基本概念 了解NMEA-0183格式数据串的组成和关于GPS的常用语句 GPS的数据串解析 二.实验材料 具有串口通讯的电脑一台 ADS1.2开发环 ...
- php implode()函数详解
php implode()函数的作用? php 中implode() 函数是返回一个由数组元素组合成的字符串,它与php explode()函数的作用是相反的,php explode() 函数是:使用 ...
- jQuery选择器中的空格问题
前几天就遇到过这样的问题,明明我用的是('tr :even').css('background','#ccc')想改变表格中行的背景色,反复试了还是没改变.还问了度娘还是没找到原因所在(当时问题描述的 ...
- R – GPU Programming for All with ‘gpuR’
INTRODUCTION GPUs (Graphic Processing Units) have become much more popular in recent years for compu ...