具体步骤:
1、启动Visual Studio,新建项目,选择Visual C# 项目、控制台应用程序,确定。
2、选择“解决方案资源管理器”,选中项目,点击右键,选择“添加引用”、“com”选项页、“Microsoft Excel 11.0 Object Library”,点击“选择”“确定”。
3、用下列代码代替“Main”方法中的注释:
Excel.Application excel;
Excel._Workbook xBk;
Excel._Worksheet xSt;
Excel._QueryTable xQt;
string Conn = "ODBC;DRIVER=SQL Server;SERVER=NB;user id=sa;DATABASE=xiaoshou";
string Select = "Select s.liushui as 流水号,y.yhname as 银行账号,s.yhpjhm as 银行票据号码,s.yhrq as 银行票据日期,s.yhje as 银行票据金额 from yinhang y,yhdata s where y.yhbh=s.yhbh";
excel = new Excel.ApplicationClass();
xBk = excel.Workbooks.Add(true);
xSt = (Excel._Worksheet)xBk.ActiveSheet;
excel.Cells[2,2] = "销售清单明细";
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Bold = true;
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Name = "黑体";
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Size = 22;
xQt = xSt.QueryTables.Add(Conn,xSt.get_Range(excel.Cells[4,2],excel.Cells[4,2]),Select);
xQt.Name = "导出所有销售明细";
xQt.FieldNames = true;
xQt.RowNumbers = false;
xQt.FillAdjacentFormulas = false;
xQt.PreserveFormatting = false;
xQt.BackgroundQuery = true;
xQt.RefreshStyle = Excel.XlCellInsertionMode.xlInsertDeleteCells;
xQt.AdjustColumnWidth = true;
xQt.RefreshPeriod = 0;
xQt.PreserveColumnInfo = true;
xQt.Refresh(xQt.BackgroundQuery);
excel.Visible = true;
4、生成、生成解决方案
5、运行