c#

位置:IT落伍者 >> c# >> 浏览文章

.NET导出Gridview到excel 带模板列显示


发布日期:2020年12月04日
 
.NET导出Gridview到excel 带模板列显示

界面内容如下

导出后显示查询到的数据如下

c#调用代码如下

protected void btnOutput_Click(object sender EventArgs e)

{

gvEquDataAllowPaging = false;

BindGridViewData()

ExcelHelper helper = new ExcelHelper()

helperExportExcel(gvEquData 设备状态信息列表+DateTimeNowToString(yyyyMMddHHmmss)+xls 设备状态信息列表

}

这里我使用了NPOI这个dll来操作excel这个dll需要去网上下载然后新建一个类用来操作excel如下

public class ExcelHelper

{

#region NPOI Excel导出

/// <summary>

/// 导出Excel

/// </summary>

/// <param name=GV>控件名称(GridView) 如有需要稍加修改可应用于DateGird等Net数据控件</param>

/// <param name=ExcleName>保存的Excel名字</param>

/// <param name=SheetName>工作簿名字</param>

/// <param name=cols>图片列 如果没有图片列 该参数可赋 NULL </param>

public void ExportExcel(GridView GV string ExcleName string SheetName)

{

HSSFWorkbook hssfworkbook = new HSSFWorkbook()

InitializeWorkbook(hssfworkbook 雄帝 Export Excel

HSSFSheet sheet = (HSSFSheet)hssfworkbookCreateSheet(SheetName)

HSSFPatriarch patriarch = (HSSFPatriarch)sheetCreateDrawingPatriarch()//插入图片所用

HSSFRow row;

HSSFCell cell;

//合并单元格信息

int startRow = ;

int startColumn = ;

int span = ;

int col = ;

//当前的格数

int rownum = ;

row = (HSSFRow)sheetCreateRow(

//添加Excel标题

for (int K = ; K < GVHeaderRowCellsCount; K++)//GVColumnsCount

{

cell = (HSSFCell)rowCreateCell(K)

if (GVHeaderRowCells[K]HasControls())

{

ControlCollection cc=GVHeaderRowCells[K]Controls;

if (ccCount <

{

if (cc[] is Literal)

{

Literal ltl = cc[] as Literal;

cellSetCellValue(ltlText)

}

else

{

cellSetCellValue(GVColumns[K]HeaderText)

}

}

else

{

if (cc[] is Literal)

{

Literal ltl = cc[] as Literal;

cellSetCellValue(ltlText)

}

else

{

cellSetCellValue(GVColumns[K]HeaderText)

}

}

}

else

{

cellSetCellValue(GVColumns[K]HeaderText)//

}

//cellSetCellValue(getCellText(GVHeaderRowCells[K]))//

}

//加载数据

for (int i = ; i < GVRowsCount; i++)//

{

row = (HSSFRow)sheetCreateRow(i +

rownum = i + ;

for (int j = ; j < GVHeaderRowCellsCount; j++)//GVColumnsCount

{

if (GVHeaderRowCells[j]ControlsCount>

{

cell = (HSSFCell)rowCreateCell(j)

if (GVHeaderRowCells[j]Controls[] is CheckBox)

{

CheckBox cbx = GVHeaderRowCells[j]Controls[] as CheckBox;

if (cbxChecked)

{

cellSetCellValue(

}

else

{

cellSetCellValue(

}

}

}

else

{

TableCell Usecell = GVRows[i]Cells[j];

if (UsecellRowSpan != || UsecellColumnSpan != )//当含有和并列(行)的时候记录该合并数据

{

startRow = i + ;//起始行

startColumn = j;//起始列

span = UsecellRowSpan;//合并的行数

col = UsecellColumnSpan;//合并的列数

}

cell = (HSSFCell)rowCreateCell(j)

//当处于合并状时忽略该格式内容

if (i + > startRow && j > startColumn && (startRow + span) > i + && (startColumn + col) > j)

{

}

else if (i + == startRow && j == startColumn)

{

//进行单元格的合并

int row = (span == ) ? : (span

int col = (col == ) ? : (col

sheetAddMergedRegion(new Region(i + j i + row + j + col))

cellSetCellValue(getCellText(GVRows[i]Cells[j]))

}

else

{

cellSetCellValue(getCellText(GVRows[i]Cells[j]))

}

}

}

}

//加载Footer部分数据

row = (HSSFRow)sheetCreateRow(rownum +

int footerAt = ;

int footSpan = ;

if (GVFooterRow != null)

{

for (int footNum = ; footNum < GVFooterRowCellsCount; footNum++)

{

TableCell footTc = GVFooterRowCells[footNum];

if (footTcColumnSpan !=

{

footSpan = footTcColumnSpan;

footerAt = footNum;

}

cell = (HSSFCell)rowCreateCell(footNum)

if (footNum > footerAt && footNum < footSpan + footerAt)

{

}

else if (footNum == footerAt)//合并单元格

{

int footercol = (footSpan == ) ? : (footSpan

sheetAddMergedRegion(new Region(rownum + footerAt rownum + footerAt + footercol))

cellSetCellValue(getCellText(GVFooterRowCells[footNum]))

}

else

{

cellSetCellValue(getCellText(footTc))

}

}

}

string path = ExcleName;

ExportToExcel(hssfworkbook ExcleName)

}

/// <summary>

/// 导出Excel

/// </summary>

/// <param name=Dt>数据源</param>

/// <param name=ExcleName>导入文件名称</param>

/// <param name=SheetName>工作薄名称</param>

/// <param name=titleArr>标题栏</param>

/// <param name=clumnArr>栏位名</param>

public void ExportExcel(DataTable Dt string ExcleName string SheetName string[] titleArr string[] clumnArr)

{

HSSFWorkbook hssfworkbook = new HSSFWorkbook()

InitializeWorkbook(hssfworkbook 雄帝 Export Excel

HSSFSheet excelSheet = (HSSFSheet)hssfworkbookCreateSheet(SheetName)

int rowCount = ;

HSSFRow newRow = (HSSFRow)excelSheetCreateRow(

rowCount++;

//循环写出列头

for (int i = ; i < titleArrLength; i++)

{

HSSFCell newCell = (HSSFCell)newRowCreateCell(i)

newCellSetCellValue(titleArr[i])

}

for (int i = ; i < DtRowsCount; i++)

{

rowCount++;

HSSFRow newRowData = (HSSFRow)excelSheetCreateRow(rowCount)

DataRow dr = DtRows[i];

for (int j = ; j < clumnArrLength; j++)

{

HSSFCell newCell = (HSSFCell)newRowCreateCell(rowCount)

newCellSetCellValue(dr[titleArr[j]]ToString())

}

}

string path = ExcleName;

ExportToExcel(hssfworkbook ExcleName)

}

//获取图片路径

string getCellText(TableCell tc)

{

string result = HttpUtilityHtmlDecode(tcText)//HttpUtilityHtmlDecode(str)

foreach (Control child in tcControls)

{

if (child is Label)

{

result = HttpUtilityHtmlDecode(((Label)child)Text)

result = resultTrim()

break;

}

}

string textLast = resultTrim()

return textLast;

}

/// <summary>

/// 对产生的Excel进行文本输入

/// </summary>

/// <param name=Path>输出路径</param>

public void WriteToFile(string Path)

{

////Write the stream data of workbook to the root directory

//FileStream file = new FileStream(Path FileModeCreate)

//hssfworkbookWrite(file)

//fileClose()

}

/// <summary>

/// 填写Excel文本属性 如有需要可以进行函数扩展 添加更多的属性值

/// </summary>

/// <param name=CompanyName>公司名称</param>

/// <param name=Subject>文档主题</param>

public void InitializeWorkbook(HSSFWorkbook hssfworkbook string CompanyName string Subject)

{

//hssfworkbook = new HSSFWorkbook()

//create a entry of DocumentSummaryInformation

DocumentSummaryInformation dsi = PropertySetFactoryCreateDocumentSummaryInformation()

dsiCompany = CompanyName;

hssfworkbookDocumentSummaryInformation = dsi;

//create a entry of SummaryInformation

SummaryInformation si = PropertySetFactoryCreateSummaryInformation()

siSubject = Subject;

hssfworkbookSummaryInformation = si;

}

MemoryStream WriteToStream(HSSFWorkbook hssfworkbook)

{

//Write the stream data of workbook to the root directory

MemoryStream file = new MemoryStream()

hssfworkbookWrite(file)

return file;

}

public void ExportToExcel(HSSFWorkbook hssfworkbook string filePath)

{

#region //以字符流的形式下载文件

//FileStream fs = new FileStream(Apppath + filePath FileModeOpen)

//byte[] bytes = new byte[(int)fsLength];

//fsRead(bytes bytesLength)

//fsClose()

#endregion

HttpContextCurrentResponseContentType = application/vndmsexcel;

HttpContextCurrentResponseAddHeader(ContentDisposition attachment; filename= +

HttpUtilityUrlEncode(filePath SystemTextEncodingUTF))

HttpContextCurrentResponseClear()

//HttpContextCurrentResponseBinaryWrite(bytes)

HttpContextCurrentResponseBinaryWrite(WriteToStream(hssfworkbook)GetBuffer())

HttpContextCurrentResponseFlush()

//HttpContextCurrentResponseEnd()

//HttpContextCurrentResponseIsClientConnected

}

#endregion

}

               

上一篇:从键盘布局开始说C#中的符号

下一篇:C#怎样用excel.dll读取excel文件