使用OleDB读取c#中的excel文件?

时间:2011-05-19 01:57:36

标签: c# excel oledb

我正在构建一个程序来将excel文件读入dataGridView。

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

namespace pro1._0
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string sConnecStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=c:\\Copy_of_Acute_HCV_2008.xls" + ";" + "Extended Properties=Excel 8.0;"; 
            OleDbConnection conObj = new OleDbConnection(sConnecStr);
            conObj.Open();
            OleDbCommand sqlCommand  = new OleDbCommand("SELECT * FROM [Sheet1$]",conObj);
            OleDbDataAdapter adaObj = new OleDbDataAdapter();
            adaObj.SelectCommand = sqlCommand;
            DataSet setObj = new DataSet();
            adaObj.Fill(setObj);
            conObj.Close();
            dataGridView1.DataSource = setObj.Tables[0];

            dataGridView1.Refresh();

        }
    }
}

当我使用一个小的excel文件时,程序运行正常但是当我使用一个大的excel文件时,它给了我这个错误

  

未处理的类型异常   'System.Data.OleDb.OleDbException'   发生在System.Data.dll

中      

其他信息:'Sheet1 $'是   不是有效的名字。确保它   不包含无效字符或   标点符号,它不是   长。

感谢

编辑:我总是使用.xls文件而不是.xlsx

1 个答案:

答案 0 :(得分:1)

protected void btnUpload_Click(object sender, EventArgs e)
{
    try
    {
        if ((txtFilePath.HasFile))
        {
            OleDbConnection conn = new OleDbConnection();
            OleDbCommand cmd = new OleDbCommand();
            OleDbDataAdapter da = new OleDbDataAdapter();
            DataSet ds = new DataSet();
            string query = null;
            string connString = "";
            string strFileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");
            string strFileType = System.IO.Path.GetExtension(txtFilePath.FileName).ToString().ToLower();

            if (strFileType == ".xls" || strFileType == ".xlsx")
            {
                txtFilePath.SaveAs(Server.MapPath("~/UploadedExcel/" + strFileName + strFileType));
            }

            string strNewPath = Server.MapPath("~/UploadedExcel/" + strFileName + strFileType);
            if (strFileType.Trim() == ".xls")
            {
                connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
            }
            else if (strFileType.Trim() == ".xlsx")
            {
                connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
            }

            conn = new OleDbConnection(connString);
            if (conn.State == ConnectionState.Closed) conn.Open();
            string SpreadSheetName = "";
            DataTable ExcelSheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

            SpreadSheetName = ExcelSheets.Rows[0]["TABLE_NAME"].ToString();
            query = "SELECT * FROM [" + SpreadSheetName + "]";
            cmd = new OleDbCommand(query, conn);
            da = new OleDbDataAdapter(cmd);
            ds = new DataSet();
            da.Fill(ds, "tab1");
         }
      }
 }