博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
导出excel的另外一种方法
阅读量:6236 次
发布时间:2019-06-22

本文共 6613 字,大约阅读时间需要 22 分钟。

据我现在所知excel有四种方法:
1.自己写的excel接口,客户端不需要装excel,见灵感之源的blog:
2.把web上的DataGrid直接导入到excel
None.gif
public
 
void
 ExportToExcel(System.Web.UI.Control ctl) 
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif
InBlock.gif            
bool CurrCtlVisible=ctl.Visible;
InBlock.gif            ctl.Visible
=true;        Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");  
InBlock.gif            Response.ContentEncoding 
= System.Text.Encoding.GetEncoding("GB2312");
InBlock.gif            Response.ContentType 
= "application/ms-excel"
InBlock.gif            ctl.Page.EnableViewState 
= false
InBlock.gif            System.IO.StringWriter tw 
= new System.IO.StringWriter(); 
InBlock.gif            System.Web.UI.HtmlTextWriter hw 
= new HtmlTextWriter(tw); 
InBlock.gif            ctl.RenderControl(hw); 
InBlock.gif            Response.Write(tw.ToString()); 
InBlock.gif            Response.End(); 
InBlock.gif            
InBlock.gif            ctl.Page.EnableViewState 
= true
InBlock.gif            ctl.Visible
=CurrCtlVisible;
ExpandedBlockEnd.gif        }
3.在引用里调用Microsoft.Office.Interop.Excel.dll,原理是把数据存到DataTable、DataView或DataGrid中,然后再把数据一格一格的赋到excel的cell里去。
见如下代码:
None.gif
public
 
class
 ExportToExcel
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif
{
InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
私有成员#region 私有成员
InBlock.gif        
// 数据的DataView
InBlock.gif
        private DataView dv=null;
InBlock.gif
InBlock.gif        
// 表格标题
InBlock.gif
        private string title=null;
InBlock.gif
InBlock.gif        
// 输出文件路径
InBlock.gif
        private string outFilePath=null;
InBlock.gif
InBlock.gif 
InBlock.gif        
// 输入文件名
InBlock.gif
        private string inputFilePath=System.Windows.Forms.Application.StartupPath+@" emplate.xls";
InBlock.gif
ExpandedSubBlockEnd.gif        
#endregion
InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
公共属性#region 公共属性
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 数据的DataView
ExpandedSubBlockEnd.gif        
/// </summary>
InBlock.gif        public DataView DV
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
set
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                dv
=value;
ExpandedSubBlockEnd.gif            }
ExpandedSubBlockEnd.gif        }
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 表格标题
ExpandedSubBlockEnd.gif        
/// </summary>
InBlock.gif        public string Title
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
set
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                title
=value;
ExpandedSubBlockEnd.gif            }
InBlock.gif            
get
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return title;
ExpandedSubBlockEnd.gif            }
ExpandedSubBlockEnd.gif        }
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 输出文件路径
ExpandedSubBlockEnd.gif        
/// </summary>
InBlock.gif        public string OutFilePath
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
set
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                outFilePath
=value;
ExpandedSubBlockEnd.gif            }
InBlock.gif            
get
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return outFilePath;
ExpandedSubBlockEnd.gif            }
ExpandedSubBlockEnd.gif        }
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 输入文件路径
ExpandedSubBlockEnd.gif        
/// </summary>
InBlock.gif        private string InputFilePath
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
set
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                inputFilePath
=value;
ExpandedSubBlockEnd.gif            }
InBlock.gif            
get
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return inputFilePath;
ExpandedSubBlockEnd.gif            }
ExpandedSubBlockEnd.gif        }
InBlock.gif
ExpandedSubBlockEnd.gif        
#endregion
       
InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
构造函数#region 构造函数
InBlock.gif
InBlock.gif        
public ExportToExcel()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockEnd.gif        }
InBlock.gif
InBlock.gif
//        public OutputExcel(DataView dv,string title)
InBlock.gif
//        {
InBlock.gif
//
InBlock.gif
//        }
InBlock.gif
ExpandedSubBlockEnd.gif        
#endregion
InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
公共方法#region 公共方法
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**///
InBlock.gif        public void CreateExcel()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
int rowIndex=4;//行起始坐标
InBlock.gif
            int colIndex=1;//列起始坐标
InBlock.gif
InBlock.gif            ApplicationClass myApp
=null;
InBlock.gif            Workbook myBook
=null;
InBlock.gif            Worksheet mySheet
=null;
InBlock.gif
InBlock.gif            
//如果文件不存在,则将模板文件拷贝一份作为输出文件
InBlock.gif
            if(!File.Exists(outFilePath))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                File.Copy(inputFilePath,outFilePath,
true);
ExpandedSubBlockEnd.gif            }
InBlock.gif
InBlock.gif            myApp
= new ApplicationClass();
InBlock.gif            myApp.Visible
=false;
InBlock.gif            
object oMissiong=System.Reflection.Missing.Value;
InBlock.gif            myApp.Workbooks.Open(outFilePath,oMissiong,oMissiong,oMissiong,oMissiong,
InBlock.gif                oMissiong,oMissiong,oMissiong,oMissiong,oMissiong,oMissiong,oMissiong,
InBlock.gif                oMissiong,oMissiong,oMissiong);
InBlock.gif            myBook
=myApp.Workbooks[1];
InBlock.gif            mySheet
=(Worksheet)myBook.ActiveSheet;
InBlock.gif
InBlock.gif            
//取得标题
InBlock.gif
            foreach(DataColumn col in dv.Table.Columns)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                colIndex
++;
InBlock.gif                mySheet.Cells[
4,colIndex] = col.ColumnName;
InBlock.gif                mySheet.get_Range(mySheet.Cells[
4,colIndex],mySheet.Cells[4,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置标题格式为居中对齐
ExpandedSubBlockEnd.gif
            }
InBlock.gif
InBlock.gif            
//取得表格中的数据
InBlock.gif
            foreach(DataRowView row in dv)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                rowIndex 
++;
InBlock.gif                colIndex 
= 1;
InBlock.gif                
foreach(DataColumn col in dv.Table.Columns)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    colIndex 
++;
InBlock.gif                    
if(col.DataType == System.Type.GetType("System.DateTime"))
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        mySheet.Cells[rowIndex,colIndex] 
= (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");
InBlock.gif                        mySheet.get_Range(mySheet.Cells[rowIndex,colIndex],mySheet.Cells[rowIndex,colIndex]).HorizontalAlignment 
= XlVAlign.xlVAlignCenter;//设置日期型的字段格式为居中对齐
ExpandedSubBlockEnd.gif
                    }
InBlock.gif                    
else  if(col.DataType == System.Type.GetType("System.String"))
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        mySheet.Cells[rowIndex,colIndex] 
= "'"+row[col.ColumnName].ToString();
InBlock.gif                        mySheet.get_Range(mySheet.Cells[rowIndex,colIndex],mySheet.Cells[rowIndex,colIndex]).HorizontalAlignment 
= XlVAlign.xlVAlignCenter;//设置字符型的字段格式为居中对齐
ExpandedSubBlockEnd.gif
                    }
InBlock.gif                    
else
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        mySheet.Cells[rowIndex,colIndex] 
= row[col.ColumnName].ToString();
ExpandedSubBlockEnd.gif                    }
ExpandedSubBlockEnd.gif                }
ExpandedSubBlockEnd.gif            }
InBlock.gif
InBlock.gif            
//加载一个合计行
InBlock.gif
            int rowSum = rowIndex + 1;
InBlock.gif            
int colSum = 2;
InBlock.gif            mySheet.Cells[rowSum,
2= "合计";
InBlock.gif            mySheet.get_Range(mySheet.Cells[rowSum,
2],mySheet.Cells[rowSum,2]).HorizontalAlignment = XlHAlign.xlHAlignCenter;
InBlock.gif
InBlock.gif            
//设置选中的部分的颜色
InBlock.gif
            mySheet.get_Range(mySheet.Cells[rowSum,colSum],mySheet.Cells[rowSum,colIndex]).Select();
InBlock.gif            mySheet.get_Range(mySheet.Cells[rowSum,colSum],mySheet.Cells[rowSum,colIndex]).Interior.ColorIndex 
= 19;//设置为浅黄色,共计有56种
InBlock.gif
InBlock.gif            
//取得整个报表的标题
InBlock.gif
            mySheet.Cells[2,2= title;
InBlock.gif
InBlock.gif            
//设置整个报表的标题格式
InBlock.gif
            mySheet.get_Range(mySheet.Cells[2,2],mySheet.Cells[2,2]).Font.Bold = true;
InBlock.gif            mySheet.get_Range(mySheet.Cells[
2,2],mySheet.Cells[2,2]).Font.Size = 22;
InBlock.gif
InBlock.gif            
//设置报表表格为最适应宽度
InBlock.gif
            mySheet.get_Range(mySheet.Cells[4,2],mySheet.Cells[rowSum,colIndex]).Select();
InBlock.gif            mySheet.get_Range(mySheet.Cells[
4,2],mySheet.Cells[rowSum,colIndex]).Columns.AutoFit();
InBlock.gif
InBlock.gif            
//设置整个报表的标题为跨列居中
InBlock.gif
            mySheet.get_Range(mySheet.Cells[2,2],mySheet.Cells[2,colIndex]).Select();
InBlock.gif            mySheet.get_Range(mySheet.Cells[
2,2],mySheet.Cells[2,colIndex]).HorizontalAlignment = XlHAlign.xlHAlignCenterAcrossSelection;
InBlock.gif
InBlock.gif            
//绘制边框
InBlock.gif
            mySheet.get_Range(mySheet.Cells[4,2],mySheet.Cells[rowSum,colIndex]).Borders.LineStyle = 1;
InBlock.gif            mySheet.get_Range(mySheet.Cells[
4,2],mySheet.Cells[rowSum,2]).Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick;//设置左边线加粗
InBlock.gif
            mySheet.get_Range(mySheet.Cells[4,2],mySheet.Cells[4,colIndex]).Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThick;//设置上边线加粗
InBlock.gif
            mySheet.get_Range(mySheet.Cells[4,colIndex],mySheet.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;//设置右边线加粗
InBlock.gif
            mySheet.get_Range(mySheet.Cells[rowSum,2],mySheet.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;//设置下边线加粗
InBlock.gif
            myBook.Save();
InBlock.gif            myBook.Close( 
true,outFilePath,true);
InBlock.gif
InBlock.gif            System.Runtime.InteropServices.Marshal.ReleaseComObject(mySheet);
InBlock.gif            System.Runtime.InteropServices.Marshal.ReleaseComObject(myBook);
InBlock.gif            System.Runtime.InteropServices.Marshal.ReleaseComObject(myApp);
InBlock.gif
InBlock.gif            myApp.Quit();
InBlock.gif            GC.Collect();
ExpandedSubBlockEnd.gif        }
ExpandedSubBlockEnd.gif        
#endregion
InBlock.gif
InBlock.gif        
ExpandedBlockEnd.gif    }
4.另外,这就是另外一种方法了,建一个SqlServer的数据源,利用Excel的外部数据源让Excel自己从数据库取数据:
None.gif
public
 
void
 ExportToExcel(
string
 pstrSql)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif
{
InBlock.gif            Excel.Application pApplication;
InBlock.gif            Excel._Workbook xBk;
InBlock.gif            Excel._Worksheet xSt;
InBlock.gif            Excel._QueryTable xQt;
InBlock.gif            
string ExcelConn = "ODBC;DRIVER=SQL Server;SERVER=localhost;UID=sa;PWD=;APP=Microsoft(R) Windows (R) 2000 Operating System;WSID=me;DATABASE=pubs";
InBlock.gif            pApplication 
= new Excel.ApplicationClass();
InBlock.gif            xBk 
= pApplication.Workbooks.Add(true);
InBlock.gif            xSt 
= (Excel._Worksheet)xBk.ActiveSheet;
InBlock.gif            pApplication.Cells[
2,2= this.title;
InBlock.gif
InBlock.gif            xSt.get_Range(pApplication.Cells[
2,2],pApplication.Cells[2,2]).Font.Bold = true;
InBlock.gif            xSt.get_Range(pApplication.Cells[
2,2],pApplication.Cells[2,2]).Font.Name = "黑体";
InBlock.gif            xSt.get_Range(pApplication.Cells[
2,2],pApplication.Cells[2,2]).Font.Size = 22;
InBlock.gif            xQt 
= xSt.QueryTables.Add(ExcelConn,xSt.get_Range(pApplication.Cells[4,2],pApplication.Cells[4,2]),pstrSql);
InBlock.gif            xQt.Name 
= "导出EXCEL";
InBlock.gif            xQt.FieldNames 
= true;
InBlock.gif            xQt.RowNumbers 
= false;
InBlock.gif            xQt.FillAdjacentFormulas 
= false;
InBlock.gif            xQt.PreserveFormatting 
= false;
InBlock.gif            xQt.BackgroundQuery 
= true;
InBlock.gif            xQt.RefreshStyle 
= Excel.XlCellInsertionMode.xlInsertDeleteCells;
InBlock.gif            xQt.AdjustColumnWidth 
= true;
InBlock.gif            xQt.RefreshPeriod 
= 0;
InBlock.gif            xQt.PreserveColumnInfo 
= true;
InBlock.gif            xQt.Refresh(xQt.BackgroundQuery);
InBlock.gif            pApplication.Visible 
= true;
ExpandedBlockEnd.gif        }
这里的pstrSql指的是sql语句。

转载地址:http://rxzia.baihongyu.com/

你可能感兴趣的文章
Android Kotlin仿微信头像裁剪图片
查看>>
Java 反射由浅入深 | 进阶必备
查看>>
React-native动态切换tab组件的方法
查看>>
2018阿里巴巴招聘笔试
查看>>
React Native常见问题(不定时更新)
查看>>
唯品会特卖升级,消费升维即将大爆发
查看>>
windows驱动创建文件符号链接
查看>>
算法-无重复字符的最长子串
查看>>
React-如何在jsx中自动补全标签
查看>>
前端加解密
查看>>
Android Studio查看Android源代码失败
查看>>
Event loop (JavaScript中的执行机制)
查看>>
谈谈对Spring IOC的理解
查看>>
axios源码分析——取消请求
查看>>
java基础(三):谈谈java异常的处理
查看>>
React 零基础入坑
查看>>
使用code-printer生成一份炫酷的简历
查看>>
SQL 中的一些小巧但常用的关键字
查看>>
从实际案例中探讨io中的延迟性能的作用
查看>>
iOS开发 • 实例——Hey, 定时器!
查看>>