C#读取EXCEL合并单元格

1、无合并单元格的Excel文档读取

string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + temp + ";Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
try
{
   //1. 建立连接
   //注意,"Extended Properties"是必需的               
   conn.Open();

   //2. 读取数据
   string query = "select * from [Sheet1$]";
   OleDbCommand oleCommand = new OleDbCommand(query, conn);
   OleDbDataAdapter da = new OleDbDataAdapter(oleCommand);
   System.Data.DataTable table = new System.Data.DataTable();

   da.Fill(table);
   //table中的数据就是Excel中的内容

}
finally
{
    conn.Close();
}

 

2、不规则Excel文件(包含合并单元格)

using Microsoft.Office.Interop.Excel;
using System.Reflection;
//------------------------------
Application app = new ApplicationClass();
try
{
    //让后台执行设置为不可见
    app.Visible = false;
    object missing = Missing.Value;
    //打开已有的工作簿
    Workbook wBook = app.Workbooks.Open("D://Excel.xls",
       missing, missing, missing, missing, missing, missing, missing,
       missing, missing, missing, missing, missing, missing, missing);

    //取得一个工作表
    //如果打开了已有的工作簿,也可以这样获取工作表
    Worksheet wSheet = wBook.ActiveSheet as Worksheet;
   
    Range curentCell = (Range)wSheet.Cells[1,1];  //只举例第一个单元格被合并
    string text = curentCell.Text;  //单元格文本
    bool temp = (bool)curentCell.MergeCells;  //表示本单元格是否是合并单元格

    Range mergeArea = curentCell.MergeArea;
    int count =mergeArea.Cells.Count; //合并列的个数(不分上下还是左右)                     
   

    //设置禁止弹出保存和覆盖的询问提示框
    app.DisplayAlerts = false;
    app.AlertBeforeOverwriting = false;

}
finally
{
    //确保Excel进程关闭
    app.Quit();
    app = null;
}

 

展开阅读全文

没有更多推荐了,返回首页