Excel 處理

1 篇文章 / 0 new
author
Excel 處理
► 方法一:採用OleDB讀取EXCEL檔:
把EXCEL檔當做一個資料來源來進行資料的讀取操作,實例如下:
public DataSet ExcelToDS(string Path) {
    string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;";
    OleDbConnection conn = new OleDbConnection(strConn);
    conn.Open();   
    string strExcel = "";    
    OleDbDataAdapter myCommand = null;
    DataSet ds = null;
    strExcel="select * from [sheet1$]";
    myCommand = new OleDbDataAdapter(strExcel, strConn);
    ds = new DataSet();
    myCommand.Fill(ds,"table1");    
    return ds;
}
對於EXCEL中的表即sheet([sheet1$])如果不是固定的可以使用下面的方法得到
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
DataTable schemaTable = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables,null);
string tableName=schemaTable.Rows[0][2].ToString().Trim();  
另外:也可進行寫入EXCEL檔,實例如下:
public void DSToExcel(string Path,DataSet oldds) {
    //先得到匯總EXCEL的DataSet 主要目的是獲得EXCEL在DataSet中的結構
    string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source ="+path1+";Extended Properties=Excel 8.0" ;
    OleDbConnection myConn = new OleDbConnection(strCon) ;
    string strCom="select * from [Sheet1$]";
    myConn.Open ( ) ;
    OleDbDataAdapter myCommand = new OleDbDataAdapter ( strCom, myConn ) ;
    ystem.Data.OleDb.OleDbCommandBuilder builder=new OleDbCommandBuilder(myCommand);
    //QuotePrefix和QuoteSuffix主要是對builder生成InsertComment命令時使用。
    builder.QuotePrefix="["; //獲取insert語句中保留字元(起始位置)
    builder.QuoteSuffix="]"; //獲取insert語句中保留字元(結束位置)
    DataSet newds=new DataSet();
    myCommand.Fill(newds ,"Table1") ;
    for(int i=0;i<oldds.Tables[0].Rows.Count;i++)
    {
        //在這裡不能使用ImportRow方法將一行導入到news中,因為ImportRow將保留原來DataRow的所有設置(DataRowState狀態不變)。
        //在使用ImportRow後newds內有值,但不能更新到Excel中因為所有導入行的DataRowState!=Added
        DataRow nrow=aDataSet.Tables["Table1"].NewRow();
        for(int j=0;j<newds.Tables[0].Columns.Count;j++)
        {
               nrow[j]=oldds.Tables[0].Rows[i][j];
        }
        newds.Tables["Table1"].Rows.Add(nrow);
    }
    myCommand.Update(newds,"Table1");
    myConn.Close();
}
► 方法二:引用的com組件:Microsoft.Office.Interop.Excel.dll   讀取EXCEL文件
首先是Excel.dll的獲取,將Office安裝目錄下的Excel.exe檔Copy到DotNet的bin目錄下,cmd到該目錄下,運行 TlbImp EXCEL.EXE Excel.dll 得到Dll檔。 再在專案中添加引用該dll檔.

//讀取EXCEL的方法   (用範圍區域讀取資料)
private void OpenExcel(string strFileName) {
    object missing = System.Reflection.Missing.Value;
        Application excel = new Application();//lauch excel application
        if (excel == null)
        {
            Response.Write("<script>alert('Can't access excel')</script>");
        }
        else
        {
            excel.Visible = false; excel.UserControl = true;
            // 以唯讀的形式打開EXCEL檔
            Workbook wb = excel.Application.Workbooks.Open(strFileName, missing, true, missing, missing, missing,
             missing, missing, missing, true, missing, missing, missing, missing, missing);
            //取得第一個工作薄
            Worksheet ws = (Worksheet)wb.Worksheets.get_Item(1);
 
            //取得總記錄行數   (包括標題列)
            int rowsint = ws.UsedRange.Cells.Rows.Count; //得到行數
            //int columnsint = mySheet.UsedRange.Cells.Columns.Count;//得到列數
 
            //取得資料範圍區域 (不包括標題列)
            Range rng1 = ws.Cells.get_Range("B2", "B" + rowsint);   //item
 
            Range rng2 = ws.Cells.get_Range("K2", "K" + rowsint); //Customer
            object[,] arryItem= (object[,])rng1.Value2;   //get range's value
            object[,] arryCus = (object[,])rng2.Value2;   
            //將新值賦給一個陣列
            string[,] arry = new string[rowsint-1, 2];
            for (int i = 1; i <= rowsint-1; i++)
            {
                //Item_Code列
                arry[i - 1, 0] =arryItem[i, 1].ToString();
                //Customer_Name列
                arry[i - 1, 1] = arryCus[i, 1].ToString();
            }
            Response.Write(arry[0, 0] + " / " + arry[0, 1] + "#" + arry[rowsint - 2, 0] + " / " + arry[rowsint - 2, 1]);
        }
         excel.Quit(); excel = null;
        Process[] procs = Process.GetProcessesByName("excel");
 
        foreach (Process pro in procs)
        {
            pro.Kill();//沒有更好的方法,只有殺掉進程
        }
        GC.Collect();
}
► 方法三:將EXCEL檔轉化成CSV(逗號分隔)的檔,用檔流讀取(等價就是讀取一個txt文字檔)。先引用命名空間:using System.Text;和using System.IO;
FileStream fs = new FileStream("d:\\Customer.csv", FileMode.Open, FileAccess.Read, FileShare.None);
StreamReader sr = new StreamReader(fs, System.Text.Encoding.GetEncoding(936));
 
string str = "";
string s = Console.ReadLine();
while (str != null)
{
    str = sr.ReadLine();
    string[] xu = new String[2];
    xu = str.Split(',');
    string ser = xu[0];
    string dse = xu[1];
     if (ser == s) {
        Console.WriteLine(dse);break;
        }
}
sr.Close();

另外也可以將資料庫資料導入到一個txt檔,實例如下:
//txt檔案名
string fn = DateTime.Now.ToString("yyyyMMddHHmmss") + "-" + "PO014" + ".txt";
 
OleDbConnection con = new OleDbConnection(conStr);
con.Open();
string sql = "select ITEM,REQD_DATE,QTY,PUR_FLG,PO_NUM from TSD_PO014";        
//OleDbCommand mycom = new OleDbCommand("select * from TSD_PO014", mycon);
//OleDbDataReader myreader = mycom.ExecuteReader(); //也可以用Reader讀取資料
DataSet ds = new DataSet();
OleDbDataAdapter oda = new OleDbDataAdapter(sql, con);
oda.Fill(ds, "PO014");
DataTable dt = ds.Tables[0];
 
FileStream fs = new FileStream(Server.MapPath("download/" + fn), FileMode.Create, FileAccess.ReadWrite);
StreamWriter strmWriter = new StreamWriter(fs);    //存入到文字檔中
 
//把標題寫入.txt文件中
//for (int i = 0; i <dt.Columns.Count;i++)
//{
//    strmWriter.Write(dt.Columns[i].ColumnName + " ");
//}
 
foreach (DataRow dr in dt.Rows)
{
    string str0, str1, str2, str3;
    string str = "|"; //數據用"|"分隔開
    str0 = dr[0].ToString();
    str1 = dr[1].ToString();
    str2 = dr[2].ToString();
    str3 = dr[3].ToString();
    str4 = dr[4].ToString().Trim();
    strmWriter.Write(str0);
    strmWriter.Write(str);
    strmWriter.Write(str1);
    strmWriter.Write(str);
    strmWriter.Write(str2);
    strmWriter.Write(str);
    strmWriter.Write(str3);
    strmWriter.WriteLine(); //換行
}
strmWriter.Flush();
strmWriter.Close();
if (con.State == ConnectionState.Open)
{
    con.Close();
}
► 使用 NPOI 套件
 該套件提供豐富的使用範例與說明, 使用上也很容易上手, 資料處理速度快.
 
► 使用 LinqtoExcel
另一套輕量套件, 對熟悉 Linq語法者應可輕易上手. 直接從 NuGet套件管理員 內安裝即可
Free Web Hosting