Aspose.Cells使用總結大全


引用:https://blog.csdn.net/u011555996/article/details/79000270

 

使用到 Aspose.Cells 插件,整理一下。

一:新建解決方案,目錄如下

  

  目錄說明:

    Program.cs - 入口類

    ExcelGenerator.cs - Aspose.Cells 操作類

    Aspose.Cell.dll - 基礎dll【文件見文章底部源代碼內】

    License.lic - Aspose.Cells 破解證書【文件見文章底部源代碼內】

      ps:由於 Aspose.Cells 插件 是收費插件,需要在使用插件前,設置一下許可證,否則在生成的Excel 中 會出現一個名叫 Evaluation Warning 的 Sheet.如圖所示:

    


二:Aspose.Cells 操作

  2.1 引入 Aspose.Cell.dll 

  

  2.2 設置 Aspose.Cell.dll 證書 License.lic

    2.2.1 設置證書。我一般都寫在生成Excel類的構造函數中了。文件路徑要和證書的位置保持一致
Excel.License l = new Excel.License();
l.SetLicense("Aid/License.lic");
    2.2.2 修改證書屬性。在解決方案中,右擊 License.lic選擇屬性,修改 Copy to Ouput Directory 屬性為 Copy always

    

  2.3 打開現有Execl 模板

復制代碼
//模板文件路徑
string Template_File_Path = @".\Template\Template.xlsx";

//  打開 Excel 模板
Workbook CurrentWorkbook = File.Exists(Template_File_Path) ? new Workbook(Template_File_Path) : new Workbook();

//  打開第一個sheet
Worksheet DetailSheet = CurrentWorkbook.Worksheets[0];
復制代碼

  2.4 寫入數據

    2.4.1 填寫數據到指定單元格
 // 比如要在 A1 位置寫入 Demo這個值

Cell itemCell = DetailSheet.Cells["A1"];

itemCell.PutValue("Demo");
    2.4.2 把DataTable寫入到Excel
復制代碼
//  獲取 Table 數據
DataTable dt = GetData();
            
//  寫入數據的起始位置
string cell_start_region = "C1";
//  獲得開始位置的行號                    
int startRow = DetailSheet.Cells[cell_start_region].Row;
//  獲得開始位置的列號  
int startColumn = DetailSheet.Cells[cell_start_region].Column;  

//  寫入Excel。參數說明,直接查閱文章底部文檔鏈接
DetailSheet.Cells.ImportDataTable(dt, false, startRow, startColumn, true, true);
復制代碼

  2.5 保存Excel

復制代碼
//  設置執行公式計算 - 如果代碼中用到公式,需要設置計算公式,導出的報表中,公式才會自動計算
CurrentWorkbook.CalculateFormula(true);

//  生成的文件名稱
string ReportFileName = string.Format("Excel_{0}.xlsx", DateTime.Now.ToString("yyyy-MM-dd"));

//  保存文件
CurrentWorkbook.Save(@".\Excel\" + ReportFileName, SaveFormat.Xlsx);
 
 
 
/新建工作簿
Workbook workbook = new Workbook(); //工作簿
Worksheet sheet = workbook.Worksheets[0]; //工作表
Cells cells = sheet.Cells;//單元格
 
sheet.Protect(ProtectionType.All, "123123", "");//保護工作表
sheet.Protection.IsSelectingLockedCellsAllowed = false;//設置只能選擇解鎖單元格
sheet.Protection.IsFormattingColumnsAllowed = true;//設置可以調整列
sheet.Protection.IsFormattingRowsAllowed = true;//設置可以調整行
 
Style style1 = workbook.Styles[workbook.Styles.Add()];//新增樣式
style1.HorizontalAlignment = TextAlignmentType.Center;//文字居中
style1.Font.Name = "宋體";//文字字體
style1.Font.Size = 22;//文字大小
style1.IsLocked = false;//單元格解鎖
style1.Font.IsBold = true;//粗體
style1.ForegroundColor = Color.FromArgb(0xaa, 0xcc, 0xbb);//設置背景色
style1.Pattern = BackgroundType.Solid; //設置背景樣式
style1.IsTextWrapped = true;//單元格內容自動換行
style1.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin; //應用邊界線 左邊界線
style1.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin; //應用邊界線 右邊界線
style1.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin; //應用邊界線 上邊界線

style1.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin; //應用邊界線 下邊界線

 

cells.Merge(0, 0, 1, 5);//合並單元格 cells[0, 0].PutValue("內容");//填寫內容 cells[0, 0].SetStyle(style1);//給單元格關聯樣式   cells.SetRowHeight(0, 20);//設置行高 cells.SetColumnWidth(1, 30);//設置列寬 cells[1, 0].Formula = "=AVERAGE(B1:E1)";//給單元格設置計算公式

//從Cells[0,0]開始創建一個2行3列的Range Range range = ws.Cells.CreateRange(0, 0, 2, 3); Cell cell = range[0, 0]; cell.Style.Font = 9; range.Style = style; range.Merge();

注意Range不能直接設置Style.必須先定義style再將style賦給Style.其他設置和Cell基本一致. Range的Style會覆蓋Cell定義的Style.另外必須先賦值再傳Style.否則可能不生效.

 

sheet.Cells[0,0].PutValue(1); sheet.Cells[1,0].PutValue(20); sheet.Cells[2,0].Formula="SUM(A1:B1)"; sheet.CalculateFormula(true); Save Excel文件的時候必須調用CalculateFormula方法計算結果.

 

//********************************************************************************

1.創建execl(不需要服務器或者客戶端安裝office)

public void DCExexl(DataTable dt) {   Workbook wb = new Workbook();   Worksheet ws = wb.Worksheets[0];   Cells cell = ws.Cells;

 

 cell[0, 0].PutValue("ID");//添加數據到第0行和第0列

 cell.SetRowHeight(0, 0);設置行高

 Aspose.Cells.Style style1 = wb.Styles[wb.Styles.Add()];  style1.HorizontalAlignment = TextAlignmentType.Right;//文字居中

 style1.Font.Name = "宋體";  style1.Font.IsBold = true;//設置粗體  style1.Font.Size = 12;//設置字體大小

 cell[0, 0].SetStyle(style1);

 cell.SetColumnWidth(0, 10.00);//列寬

Range range = cell.CreateRange(0, 0, 1, 1);//合並單元格 range.Merge();

 string FileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";  HttpResponse response = Page.Response;  response.Buffer = true;  response.Charset = "utf-8";  response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);  response.ContentEncoding = System.Text.Encoding.UTF8;  response.ContentType = "application/ms-excel";  response.BinaryWrite(wb.SaveToStream().ToArray());  response.End();

}

2.讀取execl

public DataTable GetDataTable(string path) {  Workbook workbook = new Workbook();  workbook.Open(path);  Cells cells = workbook.Worksheets[0].Cells;  DataTable dt = new DataTable();  bool d = true;//防止表頭重復加載  for (int i = 0; i < cells.MaxDataRow + 1; i++)  {   DataRow row = dt.NewRow();   for (int j = 0; j < cells.MaxDataColumn + 1; j++)    {     if (d) {      dt.Columns.Add(cells[0, j].StringValue.Trim());     }      row[j] = cells[i + 1, j].StringValue.Trim();  }   dt.Rows.Add(row);   d = false; } return dt; }

 

//*******************************************************************************

讀Excel

 

[csharp] view plain copy
 
  1.  Aspose.Cells.Workbook wk = new Aspose.Cells.Workbook();  
  2.  wk.Open(file);//打開Excel文檔  
  3.  Worksheet sht = wk.Worksheets[0];//查看文檔的sheet0內容  
  4.  Cells cells = sht.Cells;//獲取sheet0的所有單元格  
  5. if (sht==null)  
  6. {  
  7.     return false;  
  8. }  
  9. int rowCount = cells.MaxDataRow+1;//當Excel沒有一行數據時,讀取到的cells.MaxDataRow=-1,當有一行數據時cells.MaxDataRow=0     MaxDataRow:包含數據的單元格的最大行索引  
  10.   
  11. int cellCount = cells.MaxDataColumn + 1;//當Excel沒有一行數據時,讀取到的cells.MaxDataRow=-1,當有一行數據時cells.MaxDataRow=0     MaxDataRow:包含數據的單元格的最大列索引  
  12. string title = cells[j, k].Value.ToString();//獲取第j行k列單元格的內容  
  1.  
    Aspose.Cells.Workbook wk = new Aspose.Cells.Workbook();
  2.  
    wk.Open(file); //打開Excel文檔
  3.  
    Worksheet sht = wk.Worksheets[ 0];//查看文檔的sheet0內容
  4.  
    Cells cells = sht.Cells; //獲取sheet0的所有單元格
  5.  
    if (sht==null)
  6.  
    {
  7.  
    return false;
  8.  
    }
  9.  
    int rowCount = cells.MaxDataRow+1;//當Excel沒有一行數據時,讀取到的cells.MaxDataRow=-1,當有一行數據時cells.MaxDataRow=0 MaxDataRow:包含數據的單元格的最大行索引
  10.  
     
  11.  
    int cellCount = cells.MaxDataColumn + 1;//當Excel沒有一行數據時,讀取到的cells.MaxDataRow=-1,當有一行數據時cells.MaxDataRow=0 MaxDataRow:包含數據的單元格的最大列索引
  12.  
    string title = cells[j, k].Value.ToString();//獲取第j行k列單元格的內容

 

 

寫Excel

[csharp] view plain copy
 
 
print ?
  1. int _BugNoColumn = cells.MaxDataColumn+1;;//獲取最后單元格的內容  
  2. cells.InsertColumn(_BugNoColumn);//在最后單元格的后一列插入一列  
  3. Cell cell = cells[0, _BugNoColumn];//獲取插入的那一列的第一行的單元格  
  4. cell.PutValue("abc");//設置單元格的內容為"abc"  

//******************************************************************************************

 

 

上傳 

Workbook Workbook workBook = new Workbook(); 

屬性: 

 

 名稱  值類型   說明 
 Colors   Color[]   獲取或設置Excel顏色 
 ConvertNumericData   bool   獲取或設置是否將字符串轉換至數字數據 
 默認值為 true 
 DataSorter   DataSorter   獲取或設置數據分級 
 Date1904   bool   
 DefaultStyle   Aspose.Cells.Style   獲取或設置工作簿默認樣式 
 HasMacro   bool   獲取工作簿是否包含宏觀調控或宏 
 IsHScrollBarVisible   bool   獲取或設置左部滾動條(控制行) 
  默認值為true 
 IsProtected   bool   獲取工作簿保護狀態 
 IsVScrollBarVisible   bool   獲取或設置底部滾動條(控制列) 
  默認值為true 
  Language    CountryCode --枚舉類型   獲取或設置語言 
 默認為當前計算機區域 
 Password   string   獲取或設置工作簿密碼 
 ReCalcOnOpen   bool   獲取或設置是否重新計算所有打開文件的公式 
 Region   CountryCode --枚舉類型   獲取或設置工作簿區域(指當前使用者區域) 
  默認為當前計算機區域 
 Shared   bool   獲取或設置當前工作簿是否共享 
 默認為false 
 ShowTabs   bool   獲取或設置是否顯示標簽(工作表標簽) 
  默認為true 
 Styles   Styles   樣式集合 
 Worksheets   Worksheet   

 

事件: 

 

 CalculateFormula(bool ignoreError 
 ,ICustomFunction customFunction) +3 
 void   計算公式 
 ChangePalette(Color color,int index)   void   設置當前顏色在調色版中顯示順序 
 Combine(Workbook secondWorkbook)   void   聯合工作簿,將secondWorkbook 工作簿中workSheet追加到當前工作簿中 
 Copy(Workbook source)   void   拷貝工作簿到當前工作簿 
 Decrypt(string password)   void   解除工作簿密碼 
 IsColorInPalette(Color color)   bool   將color加入到當前Excel調色版 
 LoadData(string fileName)   LoadData(System.IO.Stream stream)   void   加載Excel到當前Workbook中 
 Open(string fileName, 
 FileFormatType.Default, 
 string password ); +8 
 void   打開Excel文件 
 Protect(ProtectionType.All, 
 string password); 
 void   寫保護,並設置取消工作簿保護密碼 
 RemoveExternalLinks()   void   移除外部鏈接 
 RemoveMacro()   void   移除宏 
 Replace (string PlaceHolder, 
 string newValue); +8 
 void   工作簿中類型和值完全符合的單元格,將其替換為新值或對象 
 Save(Server.UrlEncode("測試.xls"), 
  FileFormatType.Default, 
 SaveType.OpenInExcel, Response);+8 
 Void   保存工作簿 
 SaveToStream()   System.
 
 將工作簿寫入內存流中 
 Unprotect(string password);   Void   取消工作簿保護狀態 
 ValidateFormula(string formula)   bool   驗證公式 

 

-----------

  1.  
    using System;
  2.  
    using System.Collections.Generic;
  3.  
    using System.Text;
  4.  
    using Aspose.Cells;
  5.  
    using System.Data;
  6.  
     
  7.  
    namespace CRM.Common
  8.  
    {
  9.  
    public class AsposeExcel
  10.  
    {
  11.  
    private string outFileName = "";
  12.  
    private Workbook book = null;
  13.  
    private Worksheet sheet = null;
  14.  
    private log4net.ILog log = log4net.LogManager.GetLogger(typeof(AsposeExcel));
  15.  
     
  16.  
    public AsposeExcel(string outfilename,string tempfilename)
  17.  
    {
  18.  
    outFileName = outfilename;
  19.  
    book = new Workbook();
  20.  
    book.Open(tempfilename);
  21.  
    sheet = book.Worksheets[ 0];
  22.  
    }
  23.  
     
  24.  
    private void AddTitle(string title, int columnCount)
  25.  
    {
  26.  
    sheet.Cells.Merge( 0, 0, 1, columnCount);
  27.  
    sheet.Cells.Merge( 1, 0, 1, columnCount);
  28.  
     
  29.  
    Cell cell1 = sheet.Cells[ 0, 0];
  30.  
    cell1.PutValue(title);
  31.  
    cell1.Style.HorizontalAlignment = TextAlignmentType.Center;
  32.  
    cell1.Style.Font.Name = "黑體";
  33.  
    cell1.Style.Font.Size = 14;
  34.  
    cell1.Style.Font.IsBold = true;
  35.  
     
  36.  
    Cell cell2 = sheet.Cells[ 1, 0];
  37.  
    cell1.PutValue( "查詢時間:" + DateTime.Now.ToLocalTime());
  38.  
    cell2.SetStyle(cell1.Style);
  39.  
    }
  40.  
     
  41.  
    private void AddHeader(DataTable dt)
  42.  
    {
  43.  
    Cell cell = null;
  44.  
    for (int col = 0; col < dt.Columns.Count; col++)
  45.  
    {
  46.  
    cell = sheet.Cells[ 0, col];
  47.  
    cell.PutValue(dt.Columns[col].ColumnName);
  48.  
    cell.Style.Font.IsBold = true;
  49.  
    }
  50.  
    }
  51.  
     
  52.  
    private void AddBody(DataTable dt)
  53.  
    {
  54.  
    for (int r = 0; r < dt.Rows.Count; r++)
  55.  
    {
  56.  
    for (int c = 0; c < dt.Columns.Count; c++)
  57.  
    {
  58.  
    sheet.Cells[r + 3, c].PutValue(dt.Rows[r][c].ToString());
  59.  
    }
  60.  
    }
  61.  
    }
  62.  
     
  63.  
    public void DatatableToExcel(DataTable dt)
  64.  
    {
  65.  
    try
  66.  
    {
  67.  
    //sheet.Name = sheetName;
  68.  
     
  69.  
    //AddTitle(title, dt.Columns.Count);
  70.  
    //AddHeader(dt);
  71.  
    AddBody(dt);
  72.  
     
  73.  
    sheet.AutoFitColumns();
  74.  
    //sheet.AutoFitRows();
  75.  
     
  76.  
    book.Save(outFileName);
  77.  
    }
  78.  
    catch (Exception e)
  79.  
    {
  80.  
    log.Error( "導出Excel失敗!" + e.Message);
  81.  
    throw e;
  82.  
    }
  83.  
    }
  84.  
    }
  85.  
    }
  86.  
     
  87.  
     

導入就不說了。導入為datetable之后就自己操作就OK。

 

//********************************************************************************

使用Aspose.Cells 設置Excel

 
步驟:
              1.WorkBookBase 繼承自Aspose.Cells.Workbook,在WorkBookBase 中注冊
              2.使用WorkBookBase 操作Excel
      /// <summary>
      /// 創建workBook許可
      /// </summary>
      /// <author>wxl</author>
      /// <date>2012-10-15</date>
      public class WorkBookBase : Aspose.Cells.Workbook
      {
              public WorkBookBase()
              {
                      Aspose.Cells.License license = new Aspose.Cells.License();

                      string strLic = @"<License>
                                                                  <Data>
                                                                      <SerialNumber>aed83727-21cc-4a91-bea4-2607bf991c21</SerialNumber>
                                                                      <EditionType>Enterprise</EditionType>
                                                                      <Products>
                                                                          <Product>Aspose.Total</Product>
                                                                      </Products>
                                                                  </Data>
                                                                  <Signature>CxoBmxzcdRLLiQi1kzt5oSbz 9GhuyHHOBgjTf5w/wJ1V+lzjBYi8o7PvqRwkdQo4tT4dk 3PIJPbH9w5Lszei1SV/smkK8SCjR8kIWgLbOUFBvhD1 Fn9KgDAQ8B11psxIWvepKidw 8ZmDmbk9kdJbVBOkuAESXDdt DEDZMB/zL7Y=</Signature>
                                                              </License>";

                      MemoryStream ms = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(strLic));
                      license.SetLicense(ms);
 
              } 
Workbook workbook = new Workbook(); //工作簿
Worksheet sheet = workbook.Worksheets[0]; //工作表
Cells cells = sheet.Cells;//單元格

sheet.Protect(ProtectionType.All, "123123", "");//保護工作表
sheet.Protection.IsSelectingLockedCellsAl lowed = false;//設置只能選擇解鎖單元格
sheet.Protection.IsFormattingColumnsAllow ed = true;//設置可以調整列
sheet.Protection.IsFormattingRowsAllowed = true;//設置可以調整行

Style style1 = workbook.Styles[workbook.Styles.Add()];//新增樣式
style1.HorizontalAlignment = TextAlignmentType.Center;//文字居中
style1.Font.Name = "宋體";//文字字體
style1.Font.Size = 12;//文字大小
style1.IsLocked = false;//單元格解鎖
style1.Font.IsBold = true;//粗體
style1.ForegroundColor = Color.FromArgb(0x99, 0xcc, 0xff);//設置背景色
style1.Pattern = BackgroundType.Solid; //設置背景樣式
style1.IsTextWrapped = true;//單元格內容自動換行
style1.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin; //應用邊界線 左邊界線
style1.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin; //應用邊界線 右邊界線
style1.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin; //應用邊界線 上邊界線
style1.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin; //應用邊界線 下邊界線
//設置單元格背景顏色
style1.ForegroundColor  =  System.Drawing.Color.FromArgb( 153 ,  204 ,  0 );
style1.Pattern  =  BackgroundType.Solid;

cells.Merge(0, 0, 1, 5);//合並單元格
cells[0, 0].PutValue("內容");//填寫內容
cells[0, 0].SetStyle(style1);//給單元格關聯樣式
//cells[0,0].Style=style1; //給單元格關聯樣式
                                             
cells.SetRowHeight(0, 38);//設置行高

cells.SetColumnWidth(1, 20);//設置列寬

  cells[1, 0].Formula = "=AVERAGE(B1:E1)";//給單元格設置計算公式

  System.IO.MemoryStream ms = workbook.SaveToStream();//生成數據流
  byte[] bt = ms.ToArray();

  workbook.Save(@"D:\test.xls");//保存到硬盤
 

 

//***********************************************************************************************

基於Aspose.Cells.dll 封裝了對於導出的Excel的各種樣式設置,內容填充操作,目前支持邊框樣式,顏色,字體,合並單元格等操作,簡化Aspose.Cells.dll的使用

調用示例

  1.  
    /// ---------->Clom Y
  2.  
    /// |
  3.  
    /// |
  4.  
    /// |
  5.  
    /// \/ Row X
  6.  
    static void Main(string[] args)
  7.  
    {
  8.  
    object[] clom = { "列名1", "列名2", "列名3" };
  9.  
    object[] row = { "行名1", "行名2", "行名3", "行名4" };
  10.  
    String filename = "text.xlsx";
  11.  
     
  12.  
    //列標題樣式
  13.  
    CellStyle Styleclom = new CellStyle();
  14.  
    Styleclom .AllBorder = Aspose.Cells.CellBorderType.Thin;
  15.  
    Styleclom .ForegroundColor = Color.Yellow;
  16.  
    Styleclom .IsBold = true;
  17.  
    //行標題樣式
  18.  
    CellStyle Stylerow = new CellStyle();
  19.  
    Stylerow .AllBorder = Aspose.Cells.CellBorderType.Thin;
  20.  
    Stylerow .ForegroundColor = Color.ForestGreen;
  21.  
    Stylerow .IsBold = true;
  22.  
    //單元格樣式
  23.  
    CellStyle Stylebody = new CellStyle();
  24.  
    Stylebody .AllBorder = Aspose.Cells.CellBorderType.Medium;
  25.  
    Stylebody .ForegroundColor = Color.LightBlue;
  26.  
    Stylebody .IsBold = true;
  27.  
    Stylebody .IsItalic = true;
  28.  
     
  29.  
    //將樣式和內容填充到模板中
  30.  
    ExcelFormat eformat = new ExcelFormat();
  31.  
    eformat .SavePath = filename;
  32.  
    eformat .ColumnsSize = 20;
  33.  
    eformat .RowsSize = 20;
  34.  
    //直接插入標題
  35.  
    //eformat.InsertTitle(clom.ToList(), Styleclom, ExcelFormat.TitleType.列標題);
  36.  
    //eformat.InsertTitle(row.ToList(), Stylerow, ExcelFormat.TitleType.行標題);
  37.  
     
  38.  
    eformat .InsertCellRow(new CellRow(1, 4, 0, clom.ToList()), Stylerow);
  39.  
    eformat .InsertCellColm(new CellColm(1, 5, 0, row.ToList()), Styleclom);
  40.  
     
  41.  
    for (int i = 0; i < clom.Length; i++)
  42.  
    {
  43.  
    for (int j = 0; j < row.Length; j++)
  44.  
    {
  45.  
    SCell scell = new SCell();
  46.  
    scell .Txt_Obj = Convert.ToString(row[j]) + Convert.ToString(row[i]);
  47.  
    scell .X = j + 1;
  48.  
    scell .Y = i + 1;
  49.  
    scell .CStyle = Stylebody;
  50.  
    eformat .SCells.Add(scell);
  51.  
    }
  52.  
    }
  53.  
    //向Excel中寫入數據
  54.  
    ExcelMethod .InsertData(eformat, true);
  55.  
     
  56.  
    Console .WriteLine("完畢");
  57.  
    Console .ReadLine();
  58.  
    }

導出例子
這里寫圖片描述

GitHub地址

2017/11/15更新后 不再對所謂的標題行標題列作區分(在ExcelFormat對象中只保留SCells屬性,即可配置樣式的單元格集合。除此之外,新增了數據行,數據列,數據區塊的概念,方便一組規則且具有相同樣式的數據區塊插入。為確保配置樣式和插入的靈活性,所有的單元格最終匯總到SCells中等待寫入)

//********************************************************************************

Aspose.cell.dll的使用,導excel表

 

 

using System;
using System.Web;
using EF;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq; using System.IO; using Aspose.Cells; //using Microsoft.Office.Interop.Excel; //using System.Reflection; public class ToOverTimexls : IHttpHandler {     public void ProcessRequest(HttpContext context)     {         int oname = 0, years = 0, month = 0;         if (context.Request["name"] != null)         {             oname = int.Parse(context.Request["name"]);         }         if (context.Request["years"] != null)         {             years = int.Parse(context.Request["years"]);         }         if (context.Request["month"] != null)         {             month = int.Parse(context.Request["month"]);         }         //oname = 1; years = 2016; month = 1;         using (WorkRecordEntities db = new WorkRecordEntities())         {             IList<OverTime> list = db.OverTime.Where(o => o.StaffID == oname && o.StartTime.Year == years && o.StartTime.Month == month).ToList();             var name = db.Staff.Where(o => o.StaffID == oname).FirstOrDefault().FullName;             //建立一個Excel進程 Application             // string SavaFilesPath = System.Configuration.ConfigurationManager.AppSettings["DownLoad"] + Guid.NewGuid() + ".xls";             string SavaFilesPath = context.Server.MapPath("~/Download") + "\\" + Guid.NewGuid() + ".xls";             // Application excelApplication = new Application();             // //默認值為 True。如果不想在宏運行時被無窮無盡的提示和警告消息所困擾,請將本屬性設置為 False;這樣每次出現需用戶應答的消息時,Microsoft Excel             // // 將選擇默認應答。             // //如果將該屬性設置為 False,則在代碼運行結束后,Micorosoft Excel 將該屬性設置為 True,除非正運行交叉處理代碼。             // //如果使用工作簿的 SaveAs 方法覆蓋現有文件,“覆蓋”警告默認為“No”,當 DisplayAlerts 屬性值設置為 True 時,Excel 選擇“Yes”。             // excelApplication.DisplayAlerts = false;             // //  建立或打開一個 Workbook對象生成新Workbook             // Workbook workbook = excelApplication.Workbooks.Add(Missing.Value);             // //int x = 2;             // Worksheet lastWorksheet = (Worksheet)workbook.Worksheets.get_Item(workbook.Worksheets.Count);             // Worksheet newSheet = (Worksheet)workbook.Worksheets.Add(Type.Missing, lastWorksheet, Type.Missing, Type.Missing);             // //表頭             // newSheet.Cells[4, 1] = "No.(序號)";             // newSheet.Cells[4, 2] = "Date(日期)";             // newSheet.Cells[4, 3] = "Mon.~Sun.";             // newSheet.Cells[4, 4] = "From(開始)";             // newSheet.Cells[4, 5] = "To(止)";             // newSheet.Cells[4, 6] = "OT Hrs.(時間)";             // newSheet.Cells[4, 7] = "Evnt(加班事由)";             // newSheet.Cells[4, 8] = "Approve(審批)";             // newSheet.Cells[3, 4] = "To(加班時間)";             // newSheet.Cells[1,4]="加班申請表";             // newSheet.Cells[2,1]="部門:后台";              newSheet.Cells[2, 2] = "后台";             // newSheet.Cells[2, 6] = "姓名:"+name;             // //newSheet.Cells[2, 7] = name;             // newSheet.get_Range("A1", "H1").Merge(newSheet.get_Range("A1", "H1").MergeCells);             // newSheet.get_Range("A2", "D2").Merge(newSheet.get_Range("A2", "D2").MergeCells);             // newSheet.get_Range("F2", "H2").Merge(newSheet.get_Range("F2", "H2").MergeCells);             // newSheet.get_Range("A3", "A4").Merge(newSheet.get_Range("A3", "A4").MergeCells);             // newSheet.get_Range("B3", "B4").Merge(newSheet.get_Range("B3", "B4").MergeCells);             // newSheet.get_Range("C3", "C4").Merge(newSheet.get_Range("C3", "C4").MergeCells);             // newSheet.get_Range("D3", "F3").Merge(newSheet.get_Range("D3", "F3").MergeCells);             // newSheet.get_Range("G3", "G4").Merge(newSheet.get_Range("G3", "G4").MergeCells);             // newSheet.get_Range("H3", "H4").Merge(newSheet.get_Range("H3", "H4").MergeCells);             // newSheet.get_Range("A3", "H3").Interior.ColorIndex = 15;             // newSheet.get_Range("A4", "H4").Interior.ColorIndex = 15;             // Range range1 = newSheet.get_Range("A1", "H1");             // range1.HorizontalAlignment = XlHAlign.xlHAlignCenter;             // range1.WrapText = true;             // Range range = newSheet.get_Range("A3", "H4");             // range.HorizontalAlignment = XlHAlign.xlHAlignCenter;             // range.Font.Size = 10;             // range.Borders.LineStyle = 1;             // //設置邊框                      range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlMedium, XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.Black.ToArgb());                     // range.Borders.get_Item(XlBordersIndex.xlEdgeBottom).Weight = XlBorderWeight.xlMedium;             // range.WrapText = true;              var x = 3;             // var x = 5;             // for (var i = 0; i < list.Count; i++)             // {             //     newSheet.Cells[x + i, 1] = i + 1;             //     newSheet.Cells[x + i, 2] = list[i].StartTime.Month + "月" + list[i].StartTime.Day + "日";             //     newSheet.Cells[x + i, 3] = GetWeekCHA((list[i].StartTime.DayOfWeek).ToString());             //     newSheet.Cells[x + i, 4] = list[i].StartTime.ToString("yyyy/MM/dd HH:mm:ss");             //     newSheet.Cells[x + i, 5] = list[i].EndTime.ToString("yyyy/MM/dd HH:mm:ss");             //     int ts = (list[i].EndTime - list[i].StartTime).Hours;             //     newSheet.Cells[x + i, 6] = ts;             //     newSheet.Cells[x + i, 7] = list[i].Description;             //     newSheet.Cells[x + i, 8] = "";             // }             // newSheet.Cells.Columns.AutoFit();             // //刪除原來的空Sheet             // ((Worksheet)workbook.Worksheets.get_Item(1)).Delete();             // ((Worksheet)workbook.Worksheets.get_Item(1)).Delete();             // ((Worksheet)workbook.Worksheets.get_Item(1)).Delete();             // //設置默認選中是第一個Sheet 類似於Select();             // ((Worksheet)workbook.Worksheets.get_Item(1)).Activate();             // try             // {             //     workbook.Close(true, SavaFilesPath, Missing.Value);             // }             // catch (Exception e)             // {             //     throw e;             // }             // UploadExcel(SavaFilesPath, true);             // excelApplication.Quit();             Workbook workbook = new Workbook();             Worksheet worksheet = workbook.Worksheets[0];             Style styleTitle = workbook.Styles[workbook.Styles.Add()];//新增樣式                styleTitle.HorizontalAlignment = TextAlignmentType.Center;//文字居中             worksheet.PageSetup.Orientation = PageOrientationType.Landscape;//橫向打印             worksheet.PageSetup.Zoom = 100;//以100%的縮放模式打開             worksheet.PageSetup.PaperSize = PaperSizeType.PaperA4;             Range range; Cell cell;             range = worksheet.Cells.CreateRange(0, 0, 1, 8);             range.Merge();             range.RowHeight = 20;             range.ColumnWidth = 15;             cell = range[0, 0];             cell.PutValue("加班申請表");             cell.SetStyle(styleTitle);             range = worksheet.Cells.CreateRange(1, 0, 1, 2);             range.Merge();             range.RowHeight = 15;             cell = range[0, 0];             cell.PutValue("部門:后台");             range = worksheet.Cells.CreateRange(1, 4, 1, 2);             range.Merge();             range.RowHeight = 15;             cell = range[0, 0];             cell.PutValue("姓名:" + name);             //range = worksheet.Cells.CreateRange(1, 5, 1, 1);             //range.Merge();             //range.RowHeight = 15;             //cell = range[0, 0];             //cell.PutValue("方亭");             range = worksheet.Cells.CreateRange(2, 0, 2, 1);             range.Merge();             cell = range[0, 0];             cell.PutValue("No.(序號)");             cell.SetStyle(styleTitle);             range = worksheet.Cells.CreateRange(2, 1, 2, 1);             range.Merge();             cell = range[0, 0];             cell.PutValue("Date(日期)");             range = worksheet.Cells.CreateRange(2, 2, 2, 1);             range.Merge();                          cell = range[0, 0];             cell.PutValue("Mon.~Sun.");             cell.SetStyle(styleTitle);             range = worksheet.Cells.CreateRange(2, 3, 1, 3);             range.Merge();             range.ColumnWidth = 20;                          cell = range[0, 0];             cell.PutValue("To(加班時間)");             cell.SetStyle(styleTitle);             cell = worksheet.Cells[3, 3];             cell.PutValue("From(開始)");             cell.SetStyle(styleTitle);             cell = worksheet.Cells[3, 4];             cell.PutValue("To(止)");             cell.SetStyle(styleTitle);             cell = worksheet.Cells[3, 5];             cell.PutValue("OT Hrs.(時間)");             cell.SetStyle(styleTitle);             range = worksheet.Cells.CreateRange(2, 6, 2, 1);             range.Merge();             cell = range[0, 0];             cell.PutValue("Evnt(加班事由)");             cell.SetStyle(styleTitle);             range = worksheet.Cells.CreateRange(2, 7, 2, 1);             range.Merge();             cell = range[0, 0];             cell.PutValue("Approve(審批)");             cell.SetStyle(styleTitle);             for (var i = 0; i < list.Count; i++)             {                 //newSheet.Cells[x + i, 1] = i + 1;                 //newSheet.Cells[x + i, 2] = list[i].StartTime.Month + "月" + list[i].StartTime.Day + "日";                 //newSheet.Cells[x + i, 3] = GetWeekCHA((list[i].StartTime.DayOfWeek).ToString());                 //newSheet.Cells[x + i, 4] = list[i].StartTime.ToString("yyyy/MM/dd HH:mm:ss");                 //newSheet.Cells[x + i, 5] = list[i].EndTime.ToString("yyyy/MM/dd HH:mm:ss");                 //int ts = (list[i].EndTime - list[i].StartTime).Hours;                 //newSheet.Cells[x + i, 6] = ts;                 //newSheet.Cells[x + i, 7] = list[i].Description;                 //newSheet.Cells[x + i, 8] = "";                 cell = worksheet.Cells[4 + i, 0];                 cell.PutValue(i + 1);                 cell.SetStyle(styleTitle);                 cell = worksheet.Cells[4 + i, 1];                 cell.PutValue(list[i].StartTime.Month + "月" + list[i].StartTime.Day + "日");                 cell.SetStyle(styleTitle);                 cell = worksheet.Cells[4 + i, 2];                 cell.PutValue(GetWeekCHA((list[i].StartTime.DayOfWeek).ToString()));                 cell.SetStyle(styleTitle);                 cell = worksheet.Cells[4 + i, 3];                 cell.PutValue(list[i].StartTime.ToString("yyyy/MM/dd HH:mm:ss"));                 cell.SetStyle(styleTitle);                 cell = worksheet.Cells[4 + i, 4];                 cell.PutValue(list[i].EndTime.ToString("yyyy/MM/dd HH:mm:ss"));                 cell.SetStyle(styleTitle);                 int ts = (list[i].EndTime - list[i].StartTime).Hours;                 cell = worksheet.Cells[4 + i, 5];                 cell.PutValue(ts);                 cell.SetStyle(styleTitle);                 cell = worksheet.Cells[4 + i, 6];                 cell.PutValue(list[i].Description);                 cell.SetStyle(styleTitle);                 cell = worksheet.Cells[4 + i, 7];                 cell.PutValue("");                 cell.SetStyle(styleTitle);             }             workbook.Save(SavaFilesPath);             UploadExcel(SavaFilesPath, true);         }     }     ///   <summary>        ///   返回星期中文名        ///   </summary>        ///   <param   name="WeekENG">星期英文名</param>        ///   <returns></returns>        public string GetWeekCHA(string WeekENG)     {         string return_value = "";         switch (WeekENG)         {             case "Monday":                 return_value = "星期一";                 return return_value;             case "Tuesday":                 return_value = "星期二";                 return return_value;             case "Wednesday":                 return_value = "星期三";                 return return_value;             case "Thursday":                 return_value = "星期四";                 return return_value;             case "Friday":                 return_value = "星期五";                 return return_value;             case "Saturday":                 return_value = "星期六";                 return return_value;             case "Sunday":                 return_value = "星期日";                 return return_value;         }         return return_value;     }     /// <summary>     /// 提供下載     /// </summary>     /// <param name="path"></param>     /// <param name="page"
   //下載Excel
            window.location.href = "/ashx/ToExcel.ashx?project=" + probject + "&years=" + years + "&month=" + month;
 
           

 

//**************************************************************************************************

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

 

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

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

引用:Aspose.Cells.dll

復制代碼
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;

        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);
        }
        //生成數據行 
        for (int i = 0; i < Rownum; i++)
        {
            for (int k = 0; k < Colnum; k++)
            {
                cells[1 + i, k].PutValue(data.Rows[i][k].ToString());
            }
        }
        book.Save(filepath);
        GC.Collect();
    }
    catch (Exception e)
    {
        logger.Error("生成excel出錯:" + e.Message);
    }
}
復制代碼

將List的數據寫進Excel里(用的Aspose.Cells.dll)

復制代碼
/// <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;
}
復制代碼

將DataTable的數據寫進Excel里(用的Microsoft.Office.Interop.Excel.dll)(此方法在大量數據的時候很慢,例如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# WinForm 導出導入Excel/Doc 完整實例教程[使用Aspose.Cells.dll]

[csharp] view plain copy
 
  1. 1.添加引用:  
  2.   
  3. Aspose.Cells.dll(我們就叫工具包吧,可以從網上下載。關於它的操作我在“Aspose.Cells操作說明 中文版 下載 Aspose C# 導出Excel 實例”一文中的說。這里你暫時也可不理會它。)  
  4. 即使沒有安裝office也能用噢,這是一個好強的大工具。  
  5. 2.編寫Excel操作類  
  6.   
  7. using System;  
  8. using System.Collections.Generic;  
  9. using System.Text;  
  10. using Aspose.Cells;  
  11. using System.Data;  
  12. public class AsposeExcel  
  13. {  
  14.     private string outFileName = "";  
  15.     private string fullFilename = "";  
  16.     private Workbook book = null;  
  17.     private Worksheet sheet = null;  
  18.     public AsposeExcel(string outfilename, string tempfilename) //導出構造數  
  19.     {  
  20.         outFileName = outfilename;  
  21.         book = new Workbook();  
  22.         // book.Open(tempfilename);這里我們暫時不用模板  
  23.         sheet = book.Worksheets[0];  
  24.     }  
  25.     public AsposeExcel(string fullfilename) //導入構造數  
  26.     {  
  27.         fullFilename = fullfilename;  
  28.         // book = new Workbook();  
  29.         // book.Open(tempfilename);  
  30.         // sheet = book.Worksheets[0];  
  31.     }  
  32.     private void AddTitle(string title, int columnCount)  
  33.     {  
  34.         sheet.Cells.Merge(0, 0, 1, columnCount);  
  35.         sheet.Cells.Merge(1, 0, 1, columnCount);  
  36.         Cell cell1 = sheet.Cells[0, 0];  
  37.         cell1.PutValue(title);  
  38.         cell1.Style.HorizontalAlignment = TextAlignmentType.Center;  
  39.         cell1.Style.Font.Name = "黑體";  
  40.         cell1.Style.Font.Size = 14;  
  41.         cell1.Style.Font.IsBold = true;  
  42.         Cell cell2 = sheet.Cells[1, 0];  
  43.         cell1.PutValue("查詢時間:" + DateTime.Now.ToLocalTime());  
  44.         cell2.SetStyle(cell1.Style);  
  45.     }  
  46.     private void AddHeader(DataTable dt)  
  47.     {  
  48.         Cell cell = null;  
  49.         for (int col = 0; col < dt.Columns.Count; col++)  
  50.         {  
  51.             cell = sheet.Cells[0, col];  
  52.             cell.PutValue(dt.Columns[col].ColumnName);  
  53.             cell.Style.Font.IsBold = true;  
  54.         }  
  55.     }  
  56.     private void AddBody(DataTable dt)  
  57.     {  
  58.         for (int r = 0; r < dt.Rows.Count; r++)  
  59.         {  
  60.             for (int c = 0; c < dt.Columns.Count; c++)  
  61.             {  
  62.                 sheet.Cells[r + 1, c].PutValue(dt.Rows[R]­[c].ToString());  
  63.             }  
  64.         }  
  65.     }  
  66.     //導出------------下一篇會用到這個方法  
  67.     public Boolean DatatableToExcel(DataTable dt)  
  68.     {  
  69.         Boolean yn = false;  
  70.         try  
  71.         {  
  72.             //sheet.Name = sheetName;  
  73.             //AddTitle(title, dt.Columns.Count);  
  74.             //AddHeader(dt);  
  75.             AddBody(dt);  
  76.             sheet.AutoFitColumns();  
  77.             //sheet.AutoFitRows();  
  78.             book.Save(outFileName);  
  79.             yn = true;  
  80.             return yn;  
  81.         }  
  82.         catch (Exception e)  
  83.         {  
  84.             return yn;  
  85.             // throw e;  
  86.         }  
  87.     }  
  88.     public DataTable ExcelToDatatalbe()//導入  
  89.     {  
  90.         Workbook book = new Workbook();  
  91.         book.Open(fullFilename);  
  92.         Worksheet sheet = book.Worksheets[0];  
  93.         Cells cells = sheet.Cells;  
  94.         //獲取excel中的數據保存到一個datatable中  
  95.         DataTable dt_Import = cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, false);  
  96.         // dt_Import.  
  97.         return dt_Import;  
  98.     }  
  99. }[/R]  
  100.   
  101. 3. Word導出  
  102. //設置文件類型  
  103. // saveFileDialog為一個對話框控件  
  104. //如果沒有人工具欄中拉,  
  105. //可以:SaveFileDialog saveFileDialog1=new SaveFileDialog();  
  106. saveFileDialog1.Filter = "導出Excel (*.xls)|*.xls|Word (*.doc)|*.doc";  
  107. saveFileDialog1.FilterIndex = 1;  
  108. saveFileDialog1.RestoreDirectory = true;  
  109. saveFileDialog1.CreatePrompt = true;  
  110. saveFileDialog1.Title = "導出文件保存路徑";  
  111. //saveFileDialog1.ShowDialog();  
  112. //string strName = saveFileDialog1.FileName;  
  113. //設置默認文件類型顯示順序  
  114. //saveFileDialog1.FilterIndex = 2;  
  115. //保存對話框是否記憶上次打開的目錄  
  116. saveFileDialog1.RestoreDirectory = true;  
  117. //點了保存按鈕進入  
  118. if (saveFileDialog1.ShowDialog() == DialogResult.OK)  
  119. {  
  120.     //獲得文件路徑  
  121.     string localFilePath = saveFileDialog1.FileName.ToString();  
  122.     //獲取文件名,不帶路徑  
  123.     string fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1);  
  124.     //獲取文件路徑,不帶文件名  
  125.     string FilePath = localFilePath.Substring(0, localFilePath.LastIndexOf("\\"));  
  126.     //給文件名前加上時間  
  127.     string newFileName = DateTime.Now.ToString("yyyyMMdd") + fileNameExt;  
  128.     //在文件名里加字符  
  129.     //saveFileDialog1.FileName.Insert(1,"dameng");  
  130.     saveFileDialog1.FileName = FilePath + "\\" + newFileName;  
  131.     System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile();//輸出文件  
  132.     StreamWriter writer = new StreamWriter(fs);  
  133.     writer.Write("tttt");//這里就是你要導出到word的內容,內容是你什么你自已DIY  
  134.     writer.Flush();  
  135.     writer.Close();  
  136.     fs.Close();  
  137. }  
  138.   
  139. 4. 導出datatable到excel  
  140.   
  141. DataTable dt = null;  
  142. if (ds_all.Tables[0] != null)  
  143. {  
  144.     dt = ds_all.Tables[0];  
  145. }  
  146. else {  
  147.     MessageBox.Show("沒有數據記錄", "*^_^* 溫馨提示信息", MessageBoxButtons.OK);  
  148.     return;  
  149. }  
  150. //上面只是取datatable,你自己diy  
  151. AsposeExcel tt = new AsposeExcel(saveFileDialog1.FileName, "");//不用模板, saveFileDialog1是什么?上面已經說過  
  152. bool OK_NO = tt.DatatableToExcel(dt);  
  153. if (OK_NO)  
  154. {  
  155.     MessageBox.Show("導出成功", "*^_^* 溫馨提示信息", MessageBoxButtons.OK);  
  156. }  
  157. else  
  158. {  
  159. }  
  160.   
  161. 5. Excel導入  
  162. private void 導入ToolStripMenuItem_Click(object sender, EventArgs e)  
  163. {  
  164.     string localFilePath = "";  
  165.     //點了保存按鈕進入  
  166.     if (openFileDialog1.ShowDialog() == DialogResult.OK)// openFileDialog1不要再問我這是什么!  
  167.     {  
  168.         //獲得文件路徑  
  169.         localFilePath = openFileDialog1.FileName.ToString();  
  170. }  
  171.     AsposeExcel tt = new AsposeExcel(localFilePath);  
  172.     DataTable dt;  
  173.     try  
  174.     {  
  175.         dt = tt.ExcelToDatatalbe();  
  176.     }  
  177.     catch (Exception ex)  
  178.     {  
  179.         return;  
  180.     }  
  181. //有了datatable你自己就可以DIY啦,下面是我自己的你不用理  
  182. if (ddlResidence.SelectedValue == "違章確認")  
  183.     {  
  184.         if (dt.Rows[0][9].ToString() != "違章確認")  
  185.         {  
  186.                             return;  
  187.         }  
  188.         row = dt.Rows.Count;  
  189.         if (row <= 0) return;  
  190.         for (int i = 0; i < dt.Rows.Count; i++)  
  191.         {  
  192.             bllviola.Up_Confirmed_ByVnum(dt.Rows[i][6].ToString(), dt.Rows[i][9].ToString());  
  193.         }  
  194.         this.GridView1.DataSource = dt;  
  195.         GridView1.DataBind();  
  196. }  
  1.  
    1.添加引用:
  2.  
     
  3.  
    Aspose.Cells.dll(我們就叫工具包吧,可以從網上下載。關於它的操作我在“Aspose.Cells操作說明 中文版 下載 Aspose C # 導出Excel 實例”一文中的說。這里你暫時也可不理會它。)
  4.  
    即使沒有安裝office也能用噢,這是一個好強的大工具。
  5.  
    2.編寫Excel操作類
  6.  
     
  7.  
    using System;
  8.  
    using System.Collections.Generic;
  9.  
    using System.Text;
  10.  
    using Aspose.Cells;
  11.  
    using System.Data;
  12.  
    public class AsposeExcel
  13.  
    {
  14.  
    private string outFileName = "";
  15.  
    private string fullFilename = "";
  16.  
    private Workbook book = null;
  17.  
    private Worksheet sheet = null;
  18.  
    public AsposeExcel(string outfilename, string tempfilename) //導出構造數
  19.  
    {
  20.  
    outFileName = outfilename;
  21.  
    book = new Workbook();
  22.  
    // book.Open(tempfilename);這里我們暫時不用模板
  23.  
    sheet = book.Worksheets[ 0];
  24.  
    }
  25.  
    public AsposeExcel(string fullfilename) //導入構造數
  26.  
    {
  27.  
    fullFilename = fullfilename;
  28.  
    // book = new Workbook();
  29.  
    // book.Open(tempfilename);
  30.  
    // sheet = book.Worksheets[0];
  31.  
    }
  32.  
    private void AddTitle(string title, int columnCount)
  33.  
    {
  34.  
    sheet.Cells.Merge( 0, 0, 1, columnCount);
  35.  
    sheet.Cells.Merge( 1, 0, 1, columnCount);
  36.  
    Cell cell1 = sheet.Cells[ 0, 0];
  37.  
    cell1.PutValue(title);
  38.  
    cell1.Style.HorizontalAlignment = TextAlignmentType.Center;
  39.  
    cell1.Style.Font.Name = "黑體";
  40.  
    cell1.Style.Font.Size = 14;
  41.  
    cell1.Style.Font.IsBold = true;
  42.  
    Cell cell2 = sheet.Cells[ 1, 0];
  43.  
    cell1.PutValue( "查詢時間:" + DateTime.Now.ToLocalTime());
  44.  
    cell2.SetStyle(cell1.Style);
  45.  
    }
  46.  
    private void AddHeader(DataTable dt)
  47.  
    {
  48.  
    Cell cell = null;
  49.  
    for (int col = 0; col < dt.Columns.Count; col++)
  50.  
    {
  51.  
    cell = sheet.Cells[ 0, col];
  52.  
    cell.PutValue(dt.Columns[col].ColumnName);
  53.  
    cell.Style.Font.IsBold = true;
  54.  
    }
  55.  
    }
  56.  
    private void AddBody(DataTable dt)
  57.  
    {
  58.  
    for (int r = 0; r < dt.Rows.Count; r++)
  59.  
    {
  60.  
    for (int c = 0; c < dt.Columns.Count; c++)
  61.  
    {
  62.  
    sheet.Cells[r + 1, c].PutValue(dt.Rows[R]­[c].ToString());
  63.  
    }
  64.  
    }
  65.  
    }
  66.  
    //導出------------下一篇會用到這個方法
  67.  
    public Boolean DatatableToExcel(DataTable dt)
  68.  
    {
  69.  
    Boolean yn = false;
  70.  
    try
  71.  
    {
  72.  
    //sheet.Name = sheetName;
  73.  
    //AddTitle(title, dt.Columns.Count);
  74.  
    //AddHeader(dt);
  75.  
    AddBody(dt);
  76.  
    sheet.AutoFitColumns();
  77.  
    //sheet.AutoFitRows();
  78.  
    book.Save(outFileName);
  79.  
    yn = true;
  80.  
    return yn;
  81.  
    }
  82.  
    catch (Exception e)
  83.  
    {
  84.  
    return yn;
  85.  
    // throw e;
  86.  
    }
  87.  
    }
  88.  
    public DataTable ExcelToDatatalbe()//導入
  89.  
    {
  90.  
    Workbook book = new Workbook();
  91.  
    book.Open(fullFilename);
  92.  
    Worksheet sheet = book.Worksheets[ 0];
  93.  
    Cells cells = sheet.Cells;
  94.  
    //獲取excel中的數據保存到一個datatable中
  95.  
    DataTable dt_Import = cells.ExportDataTableAsString( 0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, false);
  96.  
    // dt_Import.
  97.  
    return dt_Import;
  98.  
    }
  99.  
    }[/R]
  100.  
     
  101.  
    3. Word導出
  102.  
    //設置文件類型
  103.  
    // saveFileDialog為一個對話框控件
  104.  
    //如果沒有人工具欄中拉,
  105.  
    //可以:SaveFileDialog saveFileDialog1=new SaveFileDialog();
  106.  
    saveFileDialog1.Filter = "導出Excel (*.xls)|*.xls|Word (*.doc)|*.doc";
  107.  
    saveFileDialog1.FilterIndex = 1;
  108.  
    saveFileDialog1.RestoreDirectory = true;
  109.  
    saveFileDialog1.CreatePrompt = true;
  110.  
    saveFileDialog1.Title = "導出文件保存路徑";
  111.  
    //saveFileDialog1.ShowDialog();
  112.  
    //string strName = saveFileDialog1.FileName;
  113.  
    //設置默認文件類型顯示順序
  114.  
    //saveFileDialog1.FilterIndex = 2;
  115.  
    //保存對話框是否記憶上次打開的目錄
  116.  
    saveFileDialog1.RestoreDirectory = true;
  117.  
    //點了保存按鈕進入
  118.  
    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
  119.  
    {
  120.  
    //獲得文件路徑
  121.  
    string localFilePath = saveFileDialog1.FileName.ToString();
  122.  
    //獲取文件名,不帶路徑
  123.  
    string fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1);
  124.  
    //獲取文件路徑,不帶文件名
  125.  
    string FilePath = localFilePath.Substring(0, localFilePath.LastIndexOf("\\"));
  126.  
    //給文件名前加上時間
  127.  
    string newFileName = DateTime.Now.ToString("yyyyMMdd") + fileNameExt;
  128.  
    //在文件名里加字符
  129.  
    //saveFileDialog1.FileName.Insert(1,"dameng");
  130.  
    saveFileDialog1.FileName = FilePath + "\\" + newFileName;
  131.  
    System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile(); //輸出文件
  132.  
    StreamWriter writer = new StreamWriter(fs);
  133.  
    writer.Write( "tttt");//這里就是你要導出到word的內容,內容是你什么你自已DIY
  134.  
    writer.Flush();
  135.  
    writer.Close();
  136.  
    fs.Close();
  137.  
    }
  138.  
     
  139.  
    4. 導出datatable到excel
  140.  
     
  141.  
    DataTable dt = null;
  142.  
    if (ds_all.Tables[0] != null)
  143.  
    {
  144.  
    dt = ds_all.Tables[ 0];
  145.  
    }
  146.  
    else {
  147.  
    MessageBox.Show( "沒有數據記錄", "*^_^* 溫馨提示信息", MessageBoxButtons.OK);
  148.  
    return;
  149.  
    }
  150.  
    //上面只是取datatable,你自己diy
  151.  
    AsposeExcel tt = new AsposeExcel(saveFileDialog1.FileName, "");//不用模板, saveFileDialog1是什么?上面已經說過
  152.  
    bool OK_NO = tt.DatatableToExcel(dt);
  153.  
    if (OK_NO)
  154.  
    {
  155.  
    MessageBox.Show( "導出成功", "*^_^* 溫馨提示信息", MessageBoxButtons.OK);
  156.  
    }
  157.  
    else
  158.  
    {
  159.  
    }
  160.  
     
  161.  
    5. Excel導入
  162.  
    private void 導入ToolStripMenuItem_Click(object sender, EventArgs e)
  163.  
    {
  164.  
    string localFilePath = "";
  165.  
    //點了保存按鈕進入
  166.  
    if (openFileDialog1.ShowDialog() == DialogResult.OK)// openFileDialog1不要再問我這是什么!
  167.  
    {
  168.  
    //獲得文件路徑
  169.  
    localFilePath = openFileDialog1.FileName.ToString();
  170.  
    }
  171.  
    AsposeExcel tt = new AsposeExcel(localFilePath);
  172.  
    DataTable dt;
  173.  
    try
  174.  
    {
  175.  
    dt = tt.ExcelToDatatalbe();
  176.  
    }
  177.  
    catch (Exception ex)
  178.  
    {
  179.  
    return;
  180.  
    }
  181.  
    //有了datatable你自己就可以DIY啦,下面是我自己的你不用理
  182.  
    if (ddlResidence.SelectedValue == "違章確認")
  183.  
    {
  184.  
    if (dt.Rows[0][9].ToString() != "違章確認")
  185.  
    {
  186.  
    return;
  187.  
    }
  188.  
    row = dt.Rows.Count;
  189.  
    if (row <= 0) return;
  190.  
    for (int i = 0; i < dt.Rows.Count; i++)
  191.  
    {
  192.  
    bllviola.Up_Confirmed_ByVnum(dt.Rows[i][ 6].ToString(), dt.Rows[i][9].ToString());
  193.  
    }
  194.  
    this.GridView1.DataSource = dt;
  195.  
    GridView1.DataBind();
  196.  
    }


 

//****************************************************************************************************

Aspose.Cells小實例

 
Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();Aspose.Cells.Worksheet sheet = workbook.Worksheets[0];sheet.FreezePanes(1, 1, 1, 0);//凍結第一行sheet.Cells["A1"].PutValue("ID");sheet.Cells["B1"].PutValue("手機號碼");sheet.Cells["C1"].PutValue("姓名");sheet.Cells["D1"].PutValue("出生年月");sheet.Cells["E1"].PutValue("性別");sheet.Cells["F1"].PutValue("訂購份數");sheet.Cells["G1"].PutValue("運營產品ID");sheet.Cells["H1"].PutValue("訂單狀態");sheet.Cells["I1"].PutValue("訂單成功時間");sheet.Cells["J1"].PutValue("批次ID");sheet.Cells["K1"].PutValue("支付方式");sheet.Cells["L1"].PutValue("錯誤代碼");///TODO///設置列1為文本,因為這列全是數字而且很長,不處理會變成自然數了。///這里需要注意Style是設置風格,而StyleFlag是開關,所以即使你設置了Style,沒有打開對應的StyleFlag一樣沒用Aspose.Cells.Style sc1 = workbook.Styles[workbook.Styles.Add()];sc1.ShrinkToFit = true;sc1.Number = 49;Aspose.Cells.StyleFlag scf1 = new Aspose.Cells.StyleFlag();scf1.ShrinkToFit = true;scf1.NumberFormat = true;Aspose.Cells.Column colomn1 = sheet.Cells.Columns[1];colomn1.ApplyStyle(sc1, scf1);dt =getDataTable();//得到DataTablesheet.Cells.ImportDataTable(dt, false, "A2");//從A2開始填充數據sheet.AutoFitColumns();//讓各列自適應寬度,這個很有用。workbook.Save(fileName, Aspose.Cells.FileFormatType.Excel2007Xlsx, Aspose.Cells.SaveType.OpenInExcel, response);//輸出

很多時候輸出的數據排序或者顯示的列並不一定和DataTable得到的列排序數據完全一致,那么我們可以簡單處理一下:比如把上面的

引用內容 引用內容
///TODO///設置列1為文本,因為這列全是數字而且很長,不處理會變成自然數了。///這里需要注意Style是設置風格,而StyleFlag是開關,所以即使你設置了Style,沒有打開對應的StyleFlag一樣沒用Aspose.Cells.Style sc1 = workbook.Styles[workbook.Styles.Add()];sc1.ShrinkToFit = true;sc1.Number = 49;Aspose.Cells.StyleFlag scf1 = new Aspose.Cells.StyleFlag();scf1.ShrinkToFit = true;scf1.NumberFormat = true;Aspose.Cells.Column colomn1 = sheet.Cells.Columns[1];colomn1.ApplyStyle(sc1, scf1);dt =getDataTable();//得到DataTable

替換成:

引用內容 引用內容
DataTable dt1=getDataTable();for (int i = 0; i < dt1.Rows.Count; i++){sheet.Cells[(i + 1), 0].PutValue(dt1.Rows[i]["create_time"].ToString());sheet.Cells[(i + 1), 1].PutValue(dt1.Rows[i]["holder_mobile"].ToString());sheet.Cells[(i + 1), 2].PutValue(dt1.Rows[i]["rec_name"].ToString());sheet.Cells[(i + 1), 3].PutValue(string.IsNullOrEmpty(dt1.Rows[i]["rec_sex"].ToString()) ? "" : (dt1.Rows[i]["rec_sex"].ToString() == "1") ? "男" : "女");sheet.Cells[(i + 1), 4].PutValue(dt1.Rows[i]["rec_birthday"].ToString());sheet.Cells[(i + 1), 5].PutValue(dt1.Rows[i]["base_product_code"].ToString());sheet.Cells[(i + 1), 6].PutValue(dt1.Rows[i]["sell_price"].ToString());sheet.Cells[(i + 1), 7].PutValue(dt1.Rows[i]["pay_count"].ToString());sheet.Cells[(i + 1), 8].PutValue(dt1.Rows[i]["ins_policy"].ToString());sheet.Cells[(i + 1), 9].PutValue(dt1.Rows[i]["ins_end_date"].ToString());sheet.Cells[(i + 1), 10].PutValue(Rondi.Insu.Management.Utility.StateEnum.OrderFrom(dt1.Rows[i]["order_from"].ToString()));sheet.Cells[(i + 1), 11].PutValue(Rondi.Insu.Management.Utility.StateEnum.OrderState(dt1.Rows[i]["order_state"].ToString()));}

 

//*************************************************************************************


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM