1. 程式人生 > >C# 讀寫Excel的一些方法,Aspose.Cells.dll

C# 讀寫Excel的一些方法,Aspose.Cells.dll

需求:現有2個Excel,一個7000,一個20W,7000在20W是完全存在的。現要分離20W的,拆分成19W3和7000。

條件:兩個Excel都有“登入名”,然後用“登入名”去關聯2個Excel

public void Excel()
{ 
    //獲取第一個Excel,20W
    string filePath = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "daochu/測試20W.xlsx";
    System.Data.DataTable table = GetTableFromExcel("sheet1", filePath);

    
//克隆 System.Data.DataTable table20W_new = table.Clone(); System.Data.DataTable table7000_new = table.Clone(); //獲取第二個Excel,7000 string filePath_7000 = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "daochu/測試7000.xls"; System.Data.DataTable table_7000 = GetTableFromExcel("sheet1
", filePath_7000); //迴圈20W人中的挑出來 for (int i = 0; i < table.Rows.Count; ++i) { //20W DataRow dateRow = table.Rows[i]; string login_name = dateRow["登入名"].ToString(); //7000 DataRow[] drss = table_7000.Select("登入名 = '" + login_name + "'");     
if (drss.Length > 0) { table7000_new.ImportRow(dateRow); } else { table20W_new.ImportRow(dateRow); } } //匯出Excel DataTableExport(table7000_new, AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "daochu/7000.xlsx"); DataTableExport(table20W_new, AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "daochu/22W.xlsx");
}

獲取Excel內容,轉成DataTable。

/// <summary>
/// 獲取Excel內容。
/// </summary>
/// <param name="sheetName">工作表名稱,例:sheet1</param>
/// <param name="filePath">Excel路徑</param>
/// <returns></returns>
private DataTable GetTableFromExcel(string sheetName, string filePath)
{
    const string connStrTemplate = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=Yes;\"";
    DataTable dt = null;
    if (!System.IO.File.Exists(filePath))
    {
        // don't find file
        return null;
    }
    OleDbConnection conn = new OleDbConnection(string.Format(connStrTemplate, filePath));
    try
    {
        conn.Open();
        if (sheetName == null || sheetName.Trim().Length == 0)
        {
            DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            sheetName = schemaTable.Rows[0]["TABLE_NAME"].ToString().Trim();
        }
        else
        {
            sheetName += "$";
        }

        string strSQL = "Select * From [" + sheetName + "]";
        OleDbDataAdapter da = new OleDbDataAdapter(strSQL, conn);
        DataSet ds = new DataSet();
        da.Fill(ds);
        dt = ds.Tables[0];
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        conn.Close();
    }

    return dt;
}

將DataTable的資料寫進Excel裡(用的Aspose.Cells.dll)

/// <summary>
/// DataTable資料匯出Excel
/// </summary>
/// <param name="data"></param>
/// <param name="filepath"></param>
public static void DataTableExport(DataTable data, string filepath)
{
    try
    {
        Workbook book = new Workbook(); //建立工作簿
        Worksheet sheet = book.Worksheets[0]; //建立工作表
        Cells cells = sheet.Cells; //單元格
        //建立樣式
        Aspose.Cells.Style style = book.Styles[book.Styles.Add()];
        style.Borders[Aspose.Cells.BorderType.LeftBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //應用邊界線 左邊界線  
        style.Borders[Aspose.Cells.BorderType.RightBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //應用邊界線 右邊界線  
        style.Borders[Aspose.Cells.BorderType.TopBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //應用邊界線 上邊界線  
        style.Borders[Aspose.Cells.BorderType.BottomBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //應用邊界線 下邊界線   
        style.HorizontalAlignment = TextAlignmentType.Center; //單元格內容的水平對齊方式文字居中
        style.Font.Name = "宋體"; //字型
        //style1.Font.IsBold = true; //設定粗體
        style.Font.Size = 11; //設定字型大小
        //style.ForegroundColor = System.Drawing.Color.FromArgb(153, 204, 0); //背景色
        //style.Pattern = Aspose.Cells.BackgroundType.Solid;  

        int Colnum = data.Columns.Count;//表格列數 
        int Rownum = data.Rows.Count;//表格行數 
        //生成行 列名行 
        for (int i = 0; i < Colnum; i++)
        {
            cells[0, i].PutValue(data.Columns[i].ColumnName); //新增表頭
            cells[0, i].SetStyle(style); //新增樣式
        }
        //生成資料行 
        for (int i = 0; i < Rownum; i++)
        {
            for (int k = 0; k < Colnum; k++)
            {
                cells[1 + i, k].PutValue(data.Rows[i][k].ToString()); //新增資料
                cells[1 + i, k].SetStyle(style); //新增樣式
            }
        }
        sheet.AutoFitColumns(); //自適應寬
        book.Save(filepath); //儲存
        GC.Collect();
    }
    catch (Exception e)
    {
        logger.Error("生成excel出錯:" + e.Message);
    }
}
/// <summary>
/// 匯出excel  
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data">Ilist集合</param>
/// <param name="filepath">儲存的地址</param>
public static void Export<T>(IList<T> data, string filepath)
{
    try
    {
        Workbook workbook = new Workbook();
        Worksheet sheet = (Worksheet)workbook.Worksheets[0];

        PropertyInfo[] ps = typeof(T).GetProperties();
        var colIndex = "A";
        foreach (var p in ps)
        {
            //    sheet.Cells[colIndex + 1].PutValue(p.Name);//設定表頭名稱  要求表頭為中文所以不用 p.name 為欄位名稱 可在list第一條資料為表頭名稱
            int i = 1;
            foreach (var d in data)
            {
                sheet.Cells[colIndex + i].PutValue(p.GetValue(d, null));
                i++;
            }
            colIndex = getxls_top(colIndex); //((char)(colIndex[0] + 1)).ToString();//表頭  A1/A2/
        }
        //workbook.Shared = true;
        workbook.Save(filepath);
        GC.Collect();
    }
    catch (Exception e)
    {
        logger.Error("生成excel出錯:" + e.Message);
    }
}
/// <summary>
/// 生成新的對應的列  A-Z  AA-ZZ
/// </summary>
/// <param name="top">當前列</param>
/// <returns></returns>
private static string getxls_top(string top)
{
    char[] toplist = top.ToArray();
    var itemtop = top.Last();
    string topstr = string.Empty;
    if ((char)itemtop == 90)//最後一個是Z
    {
        if (toplist.Count() == 1)
        {
            topstr = "AA";
        }
        else
        {
            toplist[0] = (char)(toplist[0] + 1);
            toplist[toplist.Count() - 1] = 'A';
            foreach (var item in toplist)
            {
                topstr += item.ToString();
            }
        }
    }
    else//最後一個不是Z  包括top為兩個字元
    {
        itemtop = (char)(itemtop + 1);
        toplist[toplist.Count() - 1] = itemtop;

        foreach (var item in toplist)
        {
            topstr += item.ToString();
        }
    }
    return topstr;
}

此方法在大量資料的時候很慢,例如22W條資料,建議使用Aspose.Cells.dll,速度快很多

/// <summary>
/// 將DataTable的資料寫進Excel裡
/// </summary>
/// <param name="tmpDataTable">DataTable資料</param>
/// <param name="strFileName">Excel路徑</param>
public static void DataTabletoExcel(System.Data.DataTable tmpDataTable, string strFileName)
{
    if (tmpDataTable == null)
    {
        return;
    }
    int rowNum = tmpDataTable.Rows.Count;
    int columnNum = tmpDataTable.Columns.Count;
    int rowIndex = 1;
    int columnIndex = 0;

    //需要引用Microsoft.Office.Interop.Excel.dll
    Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
    xlApp.DefaultFilePath = "";
    xlApp.DisplayAlerts = true;
    xlApp.SheetsInNewWorkbook = 1;
    Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);

    //將DataTable的列名匯入Excel表第一行
    foreach (DataColumn dc in tmpDataTable.Columns)
    {
        columnIndex++;
        xlApp.Cells[rowIndex, columnIndex] = dc.ColumnName;
    }

    //將DataTable中的資料匯入Excel中
    for (int i = 0; i < rowNum; i++)
    {
        rowIndex++;
        columnIndex = 0;
        for (int j = 0; j < columnNum; j++)
        {
            columnIndex++;
            xlApp.Cells[rowIndex, columnIndex] = tmpDataTable.Rows[i][j].ToString();
        }
    }
//xlBook.SaveCopyAs(HttpUtility.UrlDecode(strFileName, System.Text.Encoding.UTF8)); xlBook.SaveCopyAs(strFileName); }

原生的DataTable生成Excel(無需引用第三方dll)

/// <summary>
/// 將DataTable的資料寫進Excel裡
/// </summary>
/// <param name="tdKeChengZhuanJiaTongJi">DataTable</param>
/// <param name="sheet">sheet自定義名稱</param>
/// <param name="fileName">Excel路徑</param>
public static void DataTabletoExcel(DataTable dt, string sheet, string fileName)
{
    String sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0 Xml;\"";
    //string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HDR=Yes;'";
    //String sConnectionString = "Provider=Microsoft.ACE.OLEDB.14.0;Data Source=" + fileName + ";Extended Properties=\"Excel 14.0 Xml;\"";
    //String sConnectionString = "Provider=Microsoft.ACE.OLEDB.16.0;Data Source=" + fileName + ";Extended Properties=\"Excel 16.0 Xml;HDR=YES;\"";

    OleDbConnection cn = new OleDbConnection(sConnectionString);

    int rowNum = dt.Rows.Count;//獲取行數
    int colNum = dt.Columns.Count;//獲取列數
    string sqlText = "";//帶型別的列名
    string sqlValues = "";//
    string colCaption = "";//列名
    for (int i = 0; i < colNum; i++)
    {
        if (i != 0)
        {
            sqlText += " , ";
            colCaption += " , ";
        }
        sqlText += "[" + dt.Columns[i].Caption.ToString() + "] VarChar";//生成帶VarChar列的標題
        colCaption += "[" + dt.Columns[i].Caption.ToString() + "]";//生成列的標題
    }
    try
    {
        //開啟連線
        cn.Open();
        string sqlCreate = "CREATE TABLE [" + sheet.ToString() + "] (" + sqlText + ")";
        OleDbCommand cmd = new OleDbCommand(sqlCreate, cn);
        //建立Excel檔案
        cmd.ExecuteNonQuery();
        for (int srow = 0; srow < rowNum; srow++)
        {
            sqlValues = "";
            for (int col = 0; col < colNum; col++)
            {
                if (col != 0)
                {
                    sqlValues += " , ";
                }
                sqlValues += "'" + dt.Rows[srow][col].ToString() + "'";//拼接Value語句
            }
            String queryString = "INSERT INTO [" + sheet.ToString() + "] (" + colCaption + ") VALUES (" + sqlValues + ")";
            cmd.CommandText = queryString;
            cmd.ExecuteNonQuery();//插入資料
        }
    }
    catch
    {
    //生成日誌
    }
    finally
    {
        cn.Close();
    }
}

相關推薦

C# Excel一些方法,Aspose.Cells.dll

需求:現有2個Excel,一個7000,一個20W,7000在20W是完全存在的。現要分離20W的,拆分成19W3和7000。 條件:兩個Excel都有“登入名”,然後用“登入名”去關聯2個Excel public void Excel() { //獲取第一個Excel,20W

C#Excel表格文件NPOI方式無需安裝office .xls後綴沒問題

key 表頭 調試 成功 c++ exc reat 搜索 neu /// <summary> /// 讀Excel /// </summary> /// <param name="fileN

C#EXCEL(OLEDB方式)

  用OLEDB方式讀取EXCEL的速度是非常快的。但是當Excel資料量很大時。會非常佔用記憶體,當記憶體不夠時會丟擲記憶體溢位的異常。      OLEDB方式將Excel作為一個數據源,直接用Sql語句操作資料,並且不需要安裝Office Excel就可以使用。但缺點

C++EXCEL檔案方式比較

因為有些朋友問程式碼的問題,將OLE讀寫的程式碼分享在這個地方,大家請自己看。 http://blog.csdn.net/fullsail/article/details/8449448 C++讀取Excel的XLS檔案的方法有很多,但是也許就是因為方法太多,大家在選

c++Excel檔案

#include <fstream> #include <string> #include <iostream> #include <sstrea

C++excel檔案(三)—— 用OLE

轉自http://blog.csdn.net/yukin_xue/article/details/11209283 參考博文: http://blog.csdn.net/rekrad/article/details/7666196http://blog.csdn.net/

C#技巧【呼叫執行緒無法訪問此物件,因為另一個執行緒擁有該物件的問題的解決辦法】【C#讀寫EXCEL原始碼提示“office檢測到此檔案存在一個問題。為幫助保護您的計算機,不能開啟此檔案”的解決】

SYD8801是一款低功耗高效能藍芽低功耗SOC,集成了高效能2.4GHz射頻收發機、32位ARM Cortex-M0處理器、128kB Flash儲存器、以及豐富的數字介面。SYD8801片上集成了Balun無需阻抗匹配網路、高效率DCDC降壓轉換器,適合用於可穿戴、物聯網

C# 中 NPOI 庫 Excel 文件的方法【摘】

prot case enter this num ack npoi 工作薄 解鎖 原作:淡水網誌 NPOI 是開源的 POI 項目的.NET版,可以用來讀寫Excel,Word,PPT文件。在處理Excel文件上,NPOI 可以同時兼容 xls 和 xlsx。官網提供了一份

Pythonexcel表格的方法

python excel 表格 xls 目的:實現用python做excel的讀取、新增、修改操作。環境:ubuntu 16.04 Python 3.5.2用python讀寫文檔,一般是操作txt文件或者可以用記事本打開的文件,因為這個操作很直接,不需要導入其他模塊,但如果想要對excel表

Pythonexcel表格的方法

python excel 讀寫表格 目的:實現用python的另一種方法做excel的讀取、新增操作。環境:ubuntu 16.04 Python 3.5.2情景:之前介紹了一種操作excel文件的方法(私鏈),現在使用另一種方法讀寫excel文件,一次性讀出或寫入,讀寫也很方便,讀出為有序字典

C# App.config配置文件的方法

命名 csdn ini 手工 讀寫 xml文件 strong 我們 異常 一、配置文件概述: 應用程序配置文件是標準的 XML 文件,XML 標記和屬性是區分大小寫的。它是可以按需要更改的,開發人員可以使用配置文件來更改設置,而不必重編譯應用程序。配置文件的根節點是con

linux 上使用libxls和使用xlslibexcel方法簡介

lease stc sbin sin 1.4 讀取 iostream r++ bsp 讀取excel文件:libxls-1.4.0.zip下載地址:http://sourceforge.net/projects/libxls/安裝方法:   ./configur

Qt中快速Excel方法封裝

import mon works body oid ati ebo set 區域 #include "RwExcel.h"/*快速讀寫的機制是實現獲取有效區域只調用一次dynamicCall("Value");或setProperty("Value", var);即可, *

C#檔案的所有方法總結

計算機在最初只支援ASCII編碼,但是後來為了支援其他語言中的字元(比如漢字)以及一些特殊字元(比如€),就引入了Unicode字符集。基於Unicode字符集的編碼方式有很多,比如UTF-7、UTF-8、Unicode以及UTF-32。在Windows作業系統中,一個文字檔案的前幾個位元組

C#txt檔案的兩種方法介紹

1.新增名稱空間   System.IO;   System.Text; 2.檔案的讀取   (1).使用FileStream類進行檔案的讀取,並將它轉換成char陣列,然後輸出。 byte[] byData = new byte[100]; c

一行程式碼完成 JAVA 的 EXCEL ——EasyExcel 的方法封裝

前段時間在 github 上發現了阿里的 EasyExcel 專案,覺得挺不錯的,就寫了一個簡單的方法封裝,做到只用一個函式就完成 Excel 的匯入或者導。剛好前段時間更新修復了一些 BUG,就把我的這個封裝分享出來,請多多指教 EasyExcel

一行程式碼實現Java的Excel--EasyExcel 的方法封裝

EasyExcel 一. 依賴 首先是新增該專案的依賴,目前的版本是 1.0.2 <dependency>         <groupId>com.alibaba</groupId>        

C#使用NPOIexcel

    NPOI作為POI專案的.NET 版本,確實是能很方便的實現讀寫Excel,那麼本文就作為科普,從頭到尾實現以下通過NOPI 讀寫Excel吧!     首先需要下載NOPI,這裡是連結,下載最新版本就行http://npoi.codeplex.com/relea

C# XML檔案的方法詳細總結

XmlDocument類的屬性 屬性 說明 Attributes 當前節點的屬性集合 BaseURI 當前節點的基URI ChildNodes 節點的所有子節點 Doc

以OLE方式EXCELC++類【轉載】

◆C++中的【L"https://msdn.microsoft.com/library"】。 這個是C++標準規定的寫法。詳見以下連結: ◆VC中的 _T 和 _TEXT 和 TEXT 巨集。 _T和_TEXT和TEXT是通用的文字巨集,它們在被使用的時候,需要和字串