C MVC實現匯出到EXCEL

2021-08-09 03:31:22 字數 3091 閱讀 7283

這是excelhelper檔案

using system;

using system.collections.generic;

using system.data;

using system.io;

using system.linq;

using system.text;

using system.web;

using npoi;

using npoi.hpsf;

using npoi.hssf;

using npoi.hssf.usermodel;

using npoi.hssf.util;

using npoi.poifs;

using npoi.ss.usermodel;

using npoi.util;}}

////// datatable匯出到excel的memorystream

//////

源datatable

///表頭文字

public

static memorystream export(datatable dtsource, string strheadertext)

#region 表頭及樣式

if(!string.isnullorempty(strheadertext))

#endregion 表頭及樣式

#region 列頭及樣式

//else

// }

rowindex++;

}#endregion 列頭及樣式

}#endregion 新建表,填充表頭,填充列頭,樣式

#region 填充內容

irow datarow = sheet.createrow(rowindex);

for(int i = 0; i < theexportcols.count; i++)

//foreach(datacolumn column in dtsource.columns)

// break;

case

"system.boolean"://布林型

bool boolv = false;

bool.tryparse(drvalue, out boolv);

newcell.setcellvalue(boolv);

break;

case

"system.int16"://整型

case

"system.int32":

case

"system.int64":

case

"system.byte":

int intv = 0;

int.tryparse(drvalue, out intv);

newcell.setcellvalue(intv);

break;

case

"system.decimal"://浮點型

case

"system.double":

case

"system.single":

double doubv = 0;

double.tryparse(drvalue, out doubv);

newcell.setcellvalue(doubv);

newcell.cellstyle = decimalstyle;

break;

case

"system.dbnull"://空值處理

newcell.setcellvalue("");

break;

default:

newcell.setcellvalue("");

break;}}

#endregion 填充內容

rowindex++;

}for(int i = 0; i < theexportcols.count; i++)

using(memorystream ms = new memorystream())

}///

/// 用於web匯出

//////

源datatable

///表頭文字

///檔名

public

static

void

exportbyweb(datatable dtsource, string strheadertext, string strfilename)

///讀取excel

/// 預設第一行為標頭

//////

excel文件路徑

///public

static datatable import(string strfilename)

isheet sheet = hssfworkbook.getsheetat(0);

system.collections.ienumerator rows = sheet.getrowenumerator();

irow headerrow = sheet.getrow(0);

int cellcount = headerrow.lastcellnum;

for(int j = 0; j < cellcount; j++)

for(int i = (sheet.firstrownum + 1); i <= sheet.lastrownum; i++)

dt.rows.add(datarow);

}return dt;}}

}

這是 controller裡邊的方法

public void exporttoexcel()

excelhelper.exportbyweb(dtdata, string.empty, "經費**單位統計.xls");

}

前台html頁面的呼叫

class="btn blue"

href="/projectsupervisionunit/exporttoexcel">匯出到excela>

js實現ext grid匯出到excel

將grid作為引數傳入以下函式即可 function outputaddress grid catch e xls.visible true 設定excel為可見 var xlbook xls.workbooks.add var xlsheet xlbook.worksheets 1 var cm ...

DataGridView匯出到Excel的三個方法

region datagridview資料顯示到excel 開啟excel並將datagridview控制項中資料匯出到excel datagridview物件 是否顯示excel介面 add com microsoft excel 11.0 object library using excel m...

匯出到excel類

using system using system.data using system.configuration using system.web using system.web.security using system.web.ui using system.web.ui.webcontro...