asp.net 读取Excel多个sheet表,放入dataset中

作者&投稿:凭浦 (若有异议请与网页底部的电邮联系)
C#中如何读取excel中多个sheet-CSDN论坛~

Com组件的方式读取Excel :
这种方式需要先引用 Microsoft.Office.Interop.Excel 。首选说下这种方式的优缺点
优点:可以非常灵活的读取Excel中的数据
缺点:如果是Web站点部署在IIS上时,还需要服务器机子已安装了Excel,有时候还需要为配置IIS权限。最重要的一点因为是基于单元格方式读取的,所以数据很慢。
代码如下:
DataTable GetDataFromExcelByCom(bool hasTitle = false)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls";
openFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
openFile.Multiselect = false;
if (openFile.ShowDialog() == DialogResult.Cancel) return null;
var excelFilePath = openFile.FileName;

Excel.Application app = new Excel.Application();
Excel.Sheets sheets;
object oMissiong = System.Reflection.Missing.Value;
Excel.Workbook workbook = null;
DataTable dt = new DataTable();

try
{
if (app == null) return null;
workbook = app.Workbooks.Open(excelFilePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong,
oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong);
sheets = workbook.Worksheets;

//将数据读入到DataTable中
Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);//读取第一张表
if (worksheet == null) return null;

int iRowCount = worksheet.UsedRange.Rows.Count;
int iColCount = worksheet.UsedRange.Columns.Count;
//生成列头
for (int i = 0; i < iColCount; i++)
{
var name = "column" + i;
if (hasTitle)
{
var txt = ((Excel.Range)worksheet.Cells[1, i + 1]).Text.ToString();
if (!string.IsNullOrWhiteSpace(txt)) name = txt;
}
while (dt.Columns.Contains(name)) name = name + "_1";//重复行名称会报错。
dt.Columns.Add(new DataColumn(name, typeof(string)));
}
//生成行数据
Excel.Range range;
int rowIdx = hasTitle ? 2 : 1;
for (int iRow = rowIdx; iRow <= iRowCount; iRow++)
{
DataRow dr = dt.NewRow();
for (int iCol = 1; iCol <= iColCount; iCol++)
{
range = (Excel.Range)worksheet.Cells[iRow, iCol];
dr[iCol - 1] = (range.Value2 == null) ? "" : range.Text.ToString();
}
dt.Rows.Add(dr);
}
return dt;
}
catch { return null; }
finally
{
workbook.Close(false, oMissiong, oMissiong);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook = null;
app.Workbooks.Close();
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
app = null;
}
}

/// /// 读Excel文件 /// /// /// DataTable public static DataTable readCDEDataFile(string filePath,string condition) { DataTable dt = new DataTable(); object missing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();//lauch excel application try { Microsoft.Office.Interop.Excel.Workbook xlsBook = excel.Workbooks.Open(filePath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); if (excel == null) { //Response.Write("alert('Can't access excel')"); } else { Microsoft.Office.Interop.Excel.Worksheet wsheet = (Microsoft.Office.Interop.Excel.Worksheet)xlsBook.Worksheets.get_Item(1); string name = wsheet.Name; xlsBook.Close(false, Type.Missing, Type.Missing); excel.Quit(); string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + "Extended Properties=Excel 8.0;"; OleDbConnection oledbConn = new OleDbConnection(strConn); oledbConn.Open(); string strExcel = "select " + condition + " from [" + name + "$]"; OleDbDataAdapter myCommand = new OleDbDataAdapter(strExcel, strConn); DataSet ds = new DataSet(); myCommand.Fill(dt); oledbConn.Close(); } } catch (Exception e) { Console.Write(e.Message.ToString()); //SaveNote(e.ToString()); } finally { if (excel != null) excel.Quit(); GC.Collect(); } if (excel != null) excel.Quit(); return dt; } 取得后 循环插入就可以了

Com组件的方式读取Excel :
这种方式需要先引用 Microsoft.Office.Interop.Excel 。首选说下这种方式的优缺点
优点:可以非常灵活的读取Excel中的数据
缺点:如果是Web站点部署在IIS上时,还需要服务器机子已安装了Excel,有时候还需要为配置IIS权限。最重要的一点因为是基于单元格方式读取的,所以数据很慢。
代码如下:
DataTable GetDataFromExcelByCom(bool hasTitle = false)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls";
openFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
openFile.Multiselect = false;
if (openFile.ShowDialog() == DialogResult.Cancel) return null;
var excelFilePath = openFile.FileName;

Excel.Application app = new Excel.Application();
Excel.Sheets sheets;
object oMissiong = System.Reflection.Missing.Value;
Excel.Workbook workbook = null;
DataTable dt = new DataTable();

try
{
if (app == null) return null;
workbook = app.Workbooks.Open(excelFilePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong,
oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong);
sheets = workbook.Worksheets;

//将数据读入到DataTable中
Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);//读取第一张表
if (worksheet == null) return null;

int iRowCount = worksheet.UsedRange.Rows.Count;
int iColCount = worksheet.UsedRange.Columns.Count;
//生成列头
for (int i = 0; i < iColCount; i++)
{
var name = "column" + i;
if (hasTitle)
{
var txt = ((Excel.Range)worksheet.Cells[1, i + 1]).Text.ToString();
if (!string.IsNullOrWhiteSpace(txt)) name = txt;
}
while (dt.Columns.Contains(name)) name = name + "_1";//重复行名称会报错。
dt.Columns.Add(new DataColumn(name, typeof(string)));
}
//生成行数据
Excel.Range range;
int rowIdx = hasTitle ? 2 : 1;
for (int iRow = rowIdx; iRow <= iRowCount; iRow++)
{
DataRow dr = dt.NewRow();
for (int iCol = 1; iCol <= iColCount; iCol++)
{
range = (Excel.Range)worksheet.Cells[iRow, iCol];
dr[iCol - 1] = (range.Value2 == null) ? "" : range.Text.ToString();
}
dt.Rows.Add(dr);
}
return dt;
}
catch { return null; }
finally
{
workbook.Close(false, oMissiong, oMissiong);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook = null;
app.Workbooks.Close();
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
app = null;
}
}

你可以看一下这个
使用OleDb,让Excel操作与数据库一样简单

可以通过循环以下代码获取到每个Sheet的数据,保存到DataTable中,每次获取后,在装载到DataSet中,希望对你有用
#region 读取Excle,并将Excle中的数据保存在Datatable中
/// <summary>
/// 读取Excle,并将Excle中的数据保持在Datatable中
/// </summary>
/// <param name="filePath">要读取的文件路径</param>
/// <param name="sheetName">要读取的Excle中的工作表名</param>
/// <returns></returns>
public DataTable ImportExcelToDataTable(string filePath,string sheetName)
{
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'";
using (OleDbConnection conn = new OleDbConnection(strConn))
{
OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT*FROM[" + sheetName + "$]", strConn);
DataTable myDataTable = new DataTable();
try
{
myCommand.Fill(myDataTable);
}
catch (Exception)
{
return null;
}
return myDataTable;
}
}
#endregion

private DataSet ExcelToDS(string Path)
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties='Excel 8.0; HDR=YES; IMEX=1'";
using (OleDbConnection conn = new OleDbConnection(strConn))
{

DataSet ds = new DataSet();
try
{
conn.Open();
string strExcel = "select * from [sheet1$],[sheet2$],[sheet3$]";
OleDbDataAdapter command = new OleDbDataAdapter(strExcel, conn);
command.Fill(ds);
conn.Close();
}
catch
{
}
return ds;
}
}
以上。




休宁县17688835156: ASP如何同时读取多个表的内容 -
秦受骨刺: 你表中有外键关联没有?如果没有则通过Union来合并三个表 使用时要注意如果表B,表C字段要选取的字段类型与表A中选出来的字段类型要一样 select sTitle,sPublishDate iID from 表A union Select sCName,dCreateDate iCID from 表B Union ... 有主外键关联的话,用inner join即可

休宁县17688835156: ASP如何同时读取多个表的内容
秦受骨刺: sql="select * from 表A,表B,表C where 表A.ID=表B.ID and 表A.ID=表C.ID and 表A.title="title" order by id desc"不晓得你是这个意思不

休宁县17688835156: 如何用ASP读取Excel文件 -
秦受骨刺: Dim Conn,Driver,DBPath,Rs '建立Excel的Connection对象 Set Conn = Server.CreateObject("ADODB.Connection") Driver = "Driver={Microsoft Excel Driver (*.xls)};" DBPath = "DBQ=" & Server.MapPath( "test.xls" ) '调用Open方法打开...

休宁县17688835156: c# asp.net webfrom, 服务器端 怎么读取Excel2003中的多张图片,然后保存到服务器项目的某个目录中? -
秦受骨刺: 1、传excel文件给服务器,使用webclient.UploadFile来上传 https://msdn.microsoft.com/zh-cn/library/esst63h0(v=VS.80).aspx 非常简单.2、服务端拿到文件,进行解析.读EXCEL可以使用NPOI(第三方插件)或者微软的Office.Library.Excel.dll...

休宁县17688835156: 在asp中导入excel表中多条数据,但需避免导入重复数据 -
秦受骨刺: 你好:楼主你说的是两个需求【1是导入】【2是去掉重复的】 导入楼主已经实现,就不多说,但是如果一定要在导入的同时完成查重,并保持库中数据唯一,这会使得导入变得效率低下.我建议 方法一:导入后,再对库中数据排序,查重,删除重复数据.方法二:是在数据库外,查重,删除重复数据,在导入处理好的所有数据.以上供楼主参考.

休宁县17688835156: asp.net 将多个表导入一个excel的不同工作簿 -
秦受骨刺: 我有个这样的方法 不过代码有些多 方便的话联系我 把你的邮箱给我 这里给出核心代码try { string path = this.Server.MapPath("\\App_Data\\ContractRevert_template.xls"); HSSFWorkbook book = null; using (FileStream fs = File.OpenRead(path))...

休宁县17688835156: ASP如何调用EXCEL工作簿,或者多个工作表,我的意思是他不但要查Sheet1,还要查Sheet2.Sheet3里的数据 -
秦受骨刺: union all

休宁县17688835156: ASP.NET中如何灵活的操作一个复杂的Excel表,例如读取指定的单元格.提供点思路也可以 -
秦受骨刺: 简单的办法就是插入<script src="**.asp" type="text/javascript"></script> asp文件中写入:Response.Write "document.write('"&sql&"');"

休宁县17688835156: asp.net页面中如何获取excel你的内容. -
秦受骨刺: 后台读取excel表的内容,得到一个dataset.进而得到你要的数据.读取excel的方法应该在网上能搜的到.

休宁县17688835156: ASP如何读取EXCEL指定单元格的数据 -
秦受骨刺: '读取x行y列set Conn=Server.CreateObject("ADODB.Connection")set rs=Server.CreateObject("ADODB.Recordset")strConn="Provider=Microsoft.Jet.OLE...

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 星空见康网