.Net 读取Excel文章内容
2008-09-26 14:52
267 查看
不多说了,直接上代码,呵呵
两个函数,第一个为获取Excel文档路径,第二个读取并以DataSet类型返回该Excel中Sheet1内容
获取Excel文档路径
Code
1
/**//// <summary>
2
/// 获取Excel文档路径
3
/// </summary>
4
/// <returns></returns>
5
public string GetFilePath()
6
{
7
OpenFileDialog ofd = new OpenFileDialog();
8
ofd.Title = "打开Excel文件";
9
ofd.FileName = "";
10
ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
11
ofd.Filter = "Execl文件(*.xls)|*.xls|All files (*.*)|*.*";
12
ofd.ValidateNames = true; //文件有效性验证ValidateNames,验证用户输入是否是一个有效的Windows文件名
13
ofd.CheckFileExists = true; //验证路径有效性
14
ofd.CheckPathExists = true; //验证文件有效性
15
try
16
{
17
if (ofd.ShowDialog() == DialogResult.OK)
18
{
19
return ofd.FileName;
20
}
21
else
22
{
23
return "文件载入出错,请重新选择";
24
}
25
}
26
catch (Exception ex)
27
{
28
MessageBox.Show(ex.Message.ToString());
29
return "文件载入出错,请重新选择";
30
}
31
}
读取并返回Sheet1中的数据
Code
1
/**//// <summary>
2
/// 读取并返回Sheet1中的数据
3
/// </summary>
4
/// <param name="opnFileName"></param>
5
/// <returns></returns>
6
private DataSet ExcelToDataSet(string opnFileName)
7
{
8
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+opnFileName+";Extended Properties=/"Excel 8.0;HDR=YES;IMEX=1/"";
9
OleDbConnection conn = new OleDbConnection(strConn);
10
string strExcel = "";
11
OleDbDataAdapter myCommand = null;
12
DataSet ds = new DataSet();
13
strExcel = "select * from [sheet1$]";
14
try
15
{
16
conn.Open();
17
myCommand = new OleDbDataAdapter(strExcel, strConn);
18
myCommand.Fill(ds,"dtSource");
19
return ds;
20
}
21
catch (Exception ex)
22
{
23
MessageBox.Show("导入出错:" + ex, "错误信息");
24
return ds;
25
}
26
finally
27
{
28
conn.Close();
29
conn.Dispose();
30
}
31
}
相关文章推荐
- .NET读取Office文件内容(word、excel、ppt)
- [收藏].Net如何读取Excel文件中的内容
- .NET读取Excel文件内容
- .NET小笔记-NPOI读取excel内容到DataTable
- .NET中读取csv文件内容
- 从Excel文件中读取内容
- springMVC 读取excel内容并写入数据库
- VB.NET读取EXCEL 里面的内容
- 使用POI读取excel文件内容
- 帝国cms 文章列表页读取newstext的内容
- 使用POI读取excel文件内容
- 使用POI读取excel文件内容
- ------------------用SQL读取某目录下EXCEL文件的内容----------------
- 另一个PHP读取Excel内容的类
- 读取Excel文件,将内容存储在DataSet中
- 测试sq3数据库,读取数据库把内容输出到csv文件,附上输出到excel方法
- asp.net读取excel内容并将数据捞进DATASET中
- 解决Excel 2007的"有 XML 错误的 /xl/sharedStrings.xml"问题 (“发现不可读取的内容,是否回复此工作薄的内容...")
- ASP.NET中读取Excel内容,并显示在界面上
- Java按行读取Excel内容