ASP.NET中如何把Excel的数据导入到数据库中,最好给详细的代码和注释

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ASP.NET中如何把Excel的数据导入到数据库中,最好给详细的代码和注释相关的知识,希望对你有一定的参考价值。

你提的这个问题相当的笼统。

针对你如此高屋建瓴式的谜面,只能回答你,

整个过程一共分三步。
1. 准备好将要读取的Excel文档(远程的话,要上传到服务器),必要地时候要有格式的检查。
2. 使用C#读取Excel,转成Object或者只能转成dataTable对象。
3. 插入数据库。

看着是不是有些熟悉呢?
是滴,这和著名问题,“把大象装冰箱一共要几步”的解法在思路上基本是一样一样一样的。

PS: 没有具体的要求是无法写出具体代码的。
参考技术A public void ImportExcel(string fileName )

//string fileName = "d:\\123.xls";
string excelStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";//execl 2003
//string excelStr = "Provider= Microsoft.Ace.OleDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1'";//execl 2007以上(需要装个AccessDatabaseEngine引擎)
DataSet ds = new DataSet();
using (System.Data.OleDb.OleDbConnection cn = new OleDbConnection(excelStr))

using (OleDbDataAdapter dr = new OleDbDataAdapter("SELECT * FROM [sheet1$]", excelStr))

dr.Fill(ds);


//插入到数据库
本回答被提问者采纳

ASP.NET从数据库导出到EXCEL

C#,环境VS2005,本人菜鸟,需要详细的介绍
excel2003,需要的引用,以及是否用tlbimp生成EXCEL.DLL

给你源码自己研究一下,不会来找我

c#导出excel:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication3

public partial class Form1 : Form

private Microsoft.Office.Interop.Excel.Application m_objExcel = null;
private Microsoft.Office.Interop.Excel.Workbooks m_objBooks = null;
private Microsoft.Office.Interop.Excel._Workbook m_objBook = null;
private Microsoft.Office.Interop.Excel.Sheets m_objSheets = null;
private Microsoft.Office.Interop.Excel._Worksheet m_objSheet = null;
private Microsoft.Office.Interop.Excel.Range m_objRange = null;
//private Microsoft.Office.Interop.Excel.Font m_objFont = null;
//private Microsoft.Office.Interop.Excel.QueryTables m_objQryTables = null;
private Microsoft.Office.Interop.Excel._QueryTable m_objQryTable = null;
// Frequenty-used variable for optional arguments.
private object m_objOpt = System.Reflection.Missing.Value;
//DataBase-used variable
private System.Data.SqlClient.SqlConnection sqlConn = null;
private string strConnect = "Data Source='localhost';Password = ;User ID=sa;Initial Catalog=TEST";
private System.Data.SqlClient.SqlCommand sqlCmd = null;

//Sheets variable
private double dbSheetSize = 65535;//the hight limit number in one sheet
private int intSheetTotalSize = 0;//total record can divied sheet number
private double dbTotalSize = 0;//record total number

public Form1()

InitializeComponent();


private int GetTotalSize()

sqlConn = new System.Data.SqlClient.SqlConnection(strConnect);
sqlCmd = new System.Data.SqlClient.SqlCommand("Select Count(*) From PD_WORKBIL_MST", sqlConn);
sqlConn.Open();
dbTotalSize = (int)sqlCmd.ExecuteScalar();
sqlConn.Close();
return (int)Math.Ceiling(dbTotalSize / this.dbSheetSize);

private void DeclareExcelApp()

m_objExcel = new Microsoft.Office.Interop.Excel.Application();
m_objBooks = (Microsoft.Office.Interop.Excel.Workbooks)m_objExcel.Workbooks;
m_objBook = (Microsoft.Office.Interop.Excel._Workbook)(m_objBooks.Add(m_objOpt));
m_objSheets = (Microsoft.Office.Interop.Excel.Sheets)m_objBook.Worksheets;
intSheetTotalSize = GetTotalSize();
if (intSheetTotalSize <= 3)

if (this.dbTotalSize <= this.dbSheetSize)

this.ExportDataByQueryTable(1, false);
return;

else if (this.dbTotalSize <= this.dbSheetSize * 2)

this.ExportDataByQueryTable(1, false);
this.ExportDataByQueryTable(2, true);
return;

else

this.ExportDataByQueryTable(1, false);
this.ExportDataByQueryTable(2, true);
this.ExportDataByQueryTable(3, true);
return;


for (int i = 3; i < intSheetTotalSize; i++)

m_objSheets.Add(m_objOpt, m_objSheets.get_Item(i), m_objOpt, m_objOpt);

ExportDataByQueryTable(1, false);
for (int i = 2; i <= m_objSheets.Count; i++)

ExportDataByQueryTable(i,true);


private void SaveExcelApp()

string excelFileName = string.Empty;
SaveFileDialog sf = new SaveFileDialog();
sf.Filter = "*.xls|*.*";
if (sf.ShowDialog() == DialogResult.OK)

excelFileName = sf.FileName;

else

return;

m_objBook.SaveAs(excelFileName, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);

private void ExportDataByQueryTable(int intSheetNumber,bool blIsMoreThan)

string strQuery = string.Empty;
if (blIsMoreThan)

strQuery = "Select Top " +
this.dbSheetSize + " * From PD_WORKBIL_MST Where Not CMPID In (Select Top " +
dbSheetSize * (intSheetNumber-1) + " CMPID From PD_WORKBIL_MST)";

else

strQuery = "Select Top " +this.dbSheetSize + " * From PD_WORKBIL_MST ";


m_objSheet = (Microsoft.Office.Interop.Excel._Worksheet)(m_objSheets.get_Item(intSheetNumber));
m_objSheet.get_Range("A1", m_objOpt).set_Value(m_objOpt, "中文测试一");
m_objSheet.get_Range("B1", m_objOpt).set_Value(m_objOpt, "中文测试二");
m_objSheet.get_Range("C1", m_objOpt).set_Value(m_objOpt, "中文测试三");
m_objSheet.get_Range("D1", m_objOpt).set_Value(m_objOpt, "中文测试四");
m_objSheet.get_Range("E1", m_objOpt).set_Value(m_objOpt, "中文测试五");
m_objRange = m_objSheet.get_Range("A2", m_objOpt);
m_objQryTable = m_objSheet.QueryTables.Add("OLEDB;Provider=SQLOLEDB.1;" + strConnect, m_objRange, strQuery);
m_objQryTable.RefreshStyle = Microsoft.Office.Interop.Excel.XlCellInsertionMode.xlInsertEntireRows;
m_objQryTable.FieldNames = false;
m_objQryTable.Refresh(false);

private void button1_Click(object sender, EventArgs e)

DeclareExcelApp();
SaveExcelApp();




第二个人的:

以前做过这个东西,我把以前的学习笔记发给楼主,希望对你有点帮助.这些解决方案都不是最完美的.完美的可以用钱去买.有第三方控件卖.

例一:很简单,不也需要在服务器和客户端配置什么,但是没有封装.

string strcon = ConfigurationManager.ConnectionStrings["ConnectionStringBOB"].ToString();
SqlConnection cn = new SqlConnection(strcon);
SqlDataAdapter da = new SqlDataAdapter("SELECT ftitle,senddate,sender,RecCom FROM [Bulletin] ORDER BY [senddate]", cn);
DataSet ds = new DataSet();
da.Fill(ds, "Bulletin");
DataTable dt = ds.Tables["Bulletin"];
System.IO.StringWriter sw = new System.IO.StringWriter();
sw.WriteLine("标题\t发布时间\t发布人\t发送范围");
foreach (DataRow dr in dt.Rows)

sw.WriteLine(dr["ftitle"] + "\t " + dr["senddate"] + "\t" + dr["sender"] + "\t" + dr["RecCom"]);

sw.Close();
Response.AddHeader("Content-Disposition", "attachment;filename=SmartOA.xls");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.Write(sw);
Response.End();

例二:需要在服务器上进行配置,但实现的功能强大.
具体的配置过程如下:

1:在服务器上安装Excel.

2:文件工作目录everyone用户必须拥有修改的权限.

3:在web.config文件中加入:

<system.web>
.......//其它配置信息
<identity impersonate="true"/>
.......//其它配置信息
</system.web>

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Reflection;
using Microsoft.Office.Core;

/// <summary>
/// OutPutExcel 的摘要说明
/// </summary>
public class OutPutExcel

public OutPutExcel()

//
// TODO: 在此处添加构造函数逻辑
//

//设置文件的名称属性.
private string _xfileName;
public string xFileName

get return _xfileName;
set _xfileName = value;


public void OutputExcel(DataView dv, string titleStr,string sheetName)

GC.Collect();
Excel.Application excel;// = new Application();
int rowIndex = 4;
int colIndex = 0;

Excel._Workbook xBk;
Excel._Worksheet xSt;

excel = new Excel.ApplicationClass();

xBk = excel.Workbooks.Add(true);

xSt = (Excel._Worksheet)xBk.ActiveSheet;
xSt.Name = sheetName;
//
//取得表格中各列的标题
//
foreach (DataColumn col in dv.Table.Columns)

colIndex++;
excel.Cells[4, colIndex] = col.ColumnName;
xSt.get_Range(excel.Cells[4, colIndex], excel.Cells[4, colIndex]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;//设置标题格式为居中对齐


//
//取得表格中的数据
//
foreach (DataRowView row in dv)

rowIndex++;
colIndex = 0;
foreach (DataColumn col in dv.Table.Columns)

colIndex++;
if (col.DataType == System.Type.GetType("System.DateTime"))

excel.Cells[rowIndex, colIndex] = (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");
xSt.get_Range(excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;//设置日期型的字段格式为居中对齐

else
if (col.DataType == System.Type.GetType("System.String"))

excel.Cells[rowIndex, colIndex] = "'" + row[col.ColumnName].ToString();
xSt.get_Range(excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;//设置字符型的字段格式为居中对齐

else

excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();



//
//加载一个合计行
//
int rowSum = rowIndex;
//int colSum = 2;
//excel.Cells[rowSum, 2] = "合计";
//xSt.get_Range(excel.Cells[rowSum, 2], excel.Cells[rowSum, 2]).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
//
//设置选中的部分的颜色
//
//xSt.get_Range(excel.Cells[rowSum, colSum], excel.Cells[rowSum, colIndex]).Select();
//xSt.get_Range(excel.Cells[rowSum, colSum], excel.Cells[rowSum, colIndex]).Interior.ColorIndex = 19;//设置为浅黄色,共计有56种
//
//取得整个报表的标题
//
excel.Cells[2, 2] = titleStr;
//
//设置整个报表的标题格式
//
xSt.get_Range(excel.Cells[2, 1], excel.Cells[2, 2]).Font.Bold = true;
xSt.get_Range(excel.Cells[2, 1], excel.Cells[2, 2]).Font.Size = 12;
//
//设置报表表格为最适应宽度
//
xSt.get_Range(excel.Cells[4, 1], excel.Cells[rowSum, colIndex]).Select();
xSt.get_Range(excel.Cells[4, 1], excel.Cells[rowSum, colIndex]).Columns.AutoFit();
//
//设置整个报表的标题为跨列居中
//
xSt.get_Range(excel.Cells[2, 1], excel.Cells[2, colIndex]).Select();
xSt.get_Range(excel.Cells[2, 1], excel.Cells[2, colIndex]).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenterAcrossSelection;
//
//设置报表表格里的字体大小.
//
xSt.get_Range(excel.Cells[4, 1], excel.Cells[rowSum, colIndex]).Font.Size = 9;
//
//绘制边框
//
xSt.get_Range(excel.Cells[4, 1], excel.Cells[rowSum, colIndex]).Borders.LineStyle = 1;
xSt.get_Range(excel.Cells[4, 1], excel.Cells[rowSum, 1]).Borders[Excel.XlBordersIndex.xlEdgeLeft].Weight = Excel.XlBorderWeight.xlMedium;//设置左边线加粗
xSt.get_Range(excel.Cells[4, 1], excel.Cells[4, colIndex]).Borders[Excel.XlBordersIndex.xlEdgeTop].Weight = Excel.XlBorderWeight.xlMedium;//设置上边线加粗
xSt.get_Range(excel.Cells[4, colIndex], excel.Cells[rowSum, colIndex]).Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = Excel.XlBorderWeight.xlMedium;//设置右边线加粗
xSt.get_Range(excel.Cells[rowSum, 1], excel.Cells[rowSum, colIndex]).Borders[Excel.XlBordersIndex.xlEdgeBottom].Weight = Excel.XlBorderWeight.xlMedium;//设置下边线加粗
//
//显示效果
//
excel.Visible = false;

//xSt.Export(Server.MapPath(".")+"\\"+this.xlfile.Text+".xls",SheetExportActionEnum.ssExportActionNone,Microsoft.Office.Interop.OWC.SheetExportFormat.ssExportHTML);
xBk.SaveCopyAs(HttpContext.Current.Server.MapPath(".") + "\\" + xFileName+ ".xls");

dv.Dispose();
xBk.Close(false, null, null);

excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);
xBk = null;
excel = null;
xSt = null;
GC.Collect();
string path = HttpContext.Current.Server.MapPath(xFileName + ".xls");

System.IO.FileInfo file = new System.IO.FileInfo(path);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
// 添加头信息,为"文件下载/另存为"对话框指定默认文件名
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpContext.Current.Server.UrlEncode(file.Name));
// 添加头信息,指定文件大小,让浏览器能够显示下载进度
HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());

// 指定返回的是一个不能被客户端读取的流,必须被下载
HttpContext.Current.Response.ContentType = "application/ms-excel";

// 把文件流发送到客户端
HttpContext.Current.Response.WriteFile(file.FullName);
// 停止页面的执行

HttpContext.Current.Response.End();



调用举例:

protected void btnOutPut_Click(object sender, EventArgs e)

string ParentCode = string.Empty;
string projectunitcode = string.Empty;
//string MaterailCode = string.Empty ;
if (Request.QueryString["ParentCode"] != null)

if (Request.QueryString["ParentCode"].ToString() != string.Empty)

ParentCode = Request.QueryString["ParentCode"].ToString();


if (Request.QueryString["projectunitcode"] != null)

if (Request.QueryString["projectunitcode"].ToString() != string.Empty)

projectunitcode = Request.QueryString["projectunitcode"].ToString();



CpcecDB cpcecdb = new CpcecDB();
DataSet ds = cpcecdb.getCodeMaterialInfoss(ParentCode, projectunitcode);
DataTable dt = ds.Tables[0];
dt.Columns["MaterailCode"].ColumnName = "设备编号";
dt.Columns["MaterialName"].ColumnName = "设备名称";
dt.Columns["ManufacturerCode"].ColumnName = "生产厂编码";
dt.Columns["ManufacturerName"].ColumnName = "生产厂名称";
dt.Columns["ContractualDate"].ColumnName = "合同交货日期";
dt.Columns["AdjustDate"].ColumnName = "调整交货日期";
dt.Columns["factDate"].ColumnName = "实际完成日期";
dt.Columns["DeviceStatus"].ColumnName = "设备状态";
dt.Columns["Complete"].ColumnName = "进度情况";
dt.Columns["Quality"].ColumnName = "质量状况";
OutPutExcel outputexcel = new OutPutExcel();
outputexcel.xFileName = "huangrun124";
outputexcel.OutputExcel(dt.DefaultView, "报表","123456789");



第三个人的:

前台代码

HTML code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<br />
<asp:Button ID="btToExcel" runat="server" Text="导出Excel" OnClick="btToExcel_Click" /> </div>
</form>
</body>
</html>

后台代码

C# code
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
public partial class _Default : System.Web.UI.Page

db mydb = new db();
protected void Page_Load(object sender, EventArgs e)

getData();

public void getData()

GridView1.DataSource = mydb.getData();
GridView1.DataBind();

public override void VerifyRenderingInServerForm(Control control)




protected void btToExcel_Click(object sender, EventArgs e)

db.ExportExcel(GridView1);




using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.IO;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for db
/// </summary>
public class db

public string strCn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
public db()

//
// TODO: Add constructor logic here
//

public DataTable getData()

DataTable dt = new DataTable();
SqlDataAdapter sqlAda = new SqlDataAdapter("select id ,name from tb4 ", strCn);
sqlAda.Fill(dt);
return dt;

/// <summary>
/// 导出成为Excel
/// </summary>
/// <param name="exportTargetGridView">目标GridView</param>
public static void ExportExcel(GridView exportTargetGridView)

HttpContext.Current.Response.ClearContent();

HttpContext.Current.Response.Charset = "GB2312";

HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF7;

HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.doc");

HttpContext.Current.Response.ContentType = "application/word";

StringWriter sw = new StringWriter();

HtmlTextWriter htw = new HtmlTextWriter(sw);

exportTargetGridView.RenderControl(htw);

HttpContext.Current.Response.Write(sw.ToString());

HttpContext.Current.Response.End();

参考技术A 直接输出,先输出一个Excel头,然后输出内容!不需要引用! 参考技术B 我也是

以上是关于ASP.NET中如何把Excel的数据导入到数据库中,最好给详细的代码和注释的主要内容,如果未能解决你的问题,请参考以下文章

asp.NET 中把Excel文件导入到 Oracle 数据库中怎么做,请大家帮助

ASP.NET中如何将Excel表中的数据导入到数据库中?

asp.net怎么样把excel文件导入到数据库和导出来(紧急求助+高分)

ASP.NET把数据查询出来保存在了一个datatable里面了,之后我想把这个datatable的数据导入到access数据库

如何在 ASP.NET 中执行导入导出到 Excel 功能?

asp.net中,如何实现将page页面各个空间的属性值,导出下载到一个word或excel中