我在我的程序中使用下面的C#代码,使用oledbconnection将excel 97 - 2003电子表格数据读入数据表,并且在当前上下文中不存在该名称。
DataTable rs = null;
string path = Path.GetFullPath(filePath);
odConnection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
odConnection.Open();
OleDbCommand cmd = new OleDbCommand(); ;
OleDbDataAdapter oleda = new OleDbDataAdapter();
DataSet ds = new DataSet();
DataTable dt = odConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetName = string.Empty;
if (dt != null)
{
sheetName = dt.Rows[0]["Sheet_Name"].ToString();
}
cmd.Connection = odConnection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
oda = new OleDbDataAdapter(cmd);
oda.Fill(ds, "excelData");
rs = ds.Tables["excelData"];
答案 0 :(得分:3)
以下是如何从xlsx文件中获取特殊Sheet的所有列和行的示例。此代码从xlsx文件中获取Sheet2
的所有数据,并使用该值填充DataTable。
希望这会对你有帮助。
using System;
using System.Data;
using System.Data.OleDb;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
DataTable rs = new DataTable();
using (var odConnection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\Users\IIG\Desktop\test.xlsx;Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';"))
{
odConnection.Open();
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = odConnection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [Sheet2$]";
using (OleDbDataAdapter oleda = new OleDbDataAdapter(cmd))
{
oleda.Fill(rs);
}
}
odConnection.Close();
}
foreach(DataRow row in rs.Rows)
{
foreach(object item in row.ItemArray)
{
Console.Write(item +"\t");
}
Console.WriteLine();
}
}
}
}
答案 1 :(得分:0)
下面一行可能会导致问题 -
eventData = {
id: id,
sysid: sysid,
title: title,
start: event.start.format(),
end: event.end.format() || event.start.format(),
description: description,
otherinformation: otherinformation,
page: page,
action: action
};
尝试使用
if (dt != null)
{
sheetName = dt.Rows[0]["Sheet_Name"].ToString();
}
这应该返回工作表的名称。