小弟最近需要把数据库的一张表导出至EXCEL,因为以前没弄过,所以呢我就上网找呀找,找到了一个最基本的方法,语句如下:EXEC master..xp_cmdshell 'bcp STEPWMS.dbo.MstBOMDetail out f:\test.xls -c -q -S"Database" /U"sa" -P""'小弟我是相当兴奋,一运行,结果显示如下:output
-----------------------------------------------------------------------------NULL
开始复制...
NULL
已复制 3 行。
网络数据包大小(字节): 4096
总时钟时间(毫秒)     : 1      平均值: (每秒 3000.00 行。)
NULL(7 行受影响)于是我去F:盘下找那可爱的TEST.XLS,可是没有,我又运行了N次,可是怎么也没有,然后我继续上网找,就是没有解决呀,于是我就来向各位大侠请教了。请各位高人不吝赐教!!在下必当叩谢!

解决方案 »

  1.   

    没有试过用SQL导出EXCEL,可以先查处数据,用DataTable导出EXCEL:using System;
    using System.Windows.Forms;
    using System.Data;
    using System.Collections;
    using System.IO;
    using System.Diagnostics;namespace CHUmanager.MoonCake.Common
    {
    /// <summary>
    /// DataSetToExcel 的摘要说明。
    /// </summary>
    public class DataSetToExcel
    {
    private DateTime beforeTime;            //Excel启动之前时间
    private DateTime afterTime;             //Excel启动之后时间
    public DataSetToExcel()
    {
    //
    // TODO: 在此处添加构造函数逻辑
    //
    }
    /// <summary>
    /// 导出到Excel
    /// </summary>
    /// <param name="filename">为要保存的excel文件名</param>
    /// <param name="dt">dt为关联grid的DataTable</param>
    /// <param name="excelname">excelname为excel表的标题</param>
    public bool ExportToExcel(string filename,DataTable dt,string excelname)   
    {   
        
    if(dt==null)   return false;   

    string   saveFileName="";   
    bool   fileSaved=false;   
    SaveFileDialog   saveDialog=new   SaveFileDialog();   
    saveDialog.DefaultExt   ="xls";   
    saveDialog.Filter="Excel文件|*.xls";   
    saveDialog.FileName   =filename;   
    saveDialog.ShowDialog();   
    saveFileName=saveDialog.FileName;   
    if(saveFileName.IndexOf(":")<0)   return false;   //被点了取消    beforeTime = DateTime.Now;//Excel启动之前时间
    Excel.Application   xlApp=new   Excel.Application();   
    afterTime = DateTime.Now;//Excel启动之后时间
        
    if(xlApp==null)   
    {   
    MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");   
    return false;   
    }   
        
    Excel.Workbooks   workbooks=xlApp.Workbooks;   
    Excel.Workbook   workbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);   
    Excel.Worksheet   worksheet=(Excel.Worksheet)workbook.Worksheets[1];//取得sheet1   
    Excel.Range   range;   
        
        
    long   totalCount=dt.Rows.Count;   
    long   rowRead=0;   
    float  percent=0;   

    //合并单元格
    Excel.Range rH = worksheet.get_Range("A1",intToString(dt.Columns.Count)+"1");
    rH.Merge(0);
    //写如标题
    worksheet.Cells[1,1]=excelname; 
    //标题样式
    range=(Excel.Range)worksheet.Cells[1,1];   
    range.Interior.ColorIndex   =   15; 
    range.Font.Size = 14;
    range.Font.Name = "隶书";
    range.Font.Bold   =   true;  
    range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
    //写入字段   
    for(int   i=0;i<dt.Columns.Count;i++)   
    {   
    worksheet.Cells[2,i+1]=dt.Columns[i].ColumnName; 
    //获取字段样式
    range=(Excel.Range)worksheet.Cells[2,i+1];    
    range.Font.Bold   =   true;   
            
    }   
    //写入数值    
    for(int   r=0;r<dt.Rows.Count;r++)   
    {   
    for(int   i=0;i<dt.Columns.Count;i++)   
    {   
    worksheet.Cells[r+3,i+1]=dt.Rows[r][i];             
    }   
    rowRead++;   
    percent=((float)(100*rowRead))/totalCount;              
    System.Windows.Forms   .Application.DoEvents();   
    }   
        
    range=worksheet.get_Range(worksheet.Cells[2,1],worksheet.Cells[dt.Rows.Count+2,dt.Columns.Count]);   
    range.BorderAround(Excel.XlLineStyle.xlContinuous,Excel.XlBorderWeight.xlThin,Excel.XlColorIndex.xlColorIndexAutomatic,null);   
              
    range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex   =   Excel.XlColorIndex.xlColorIndexAutomatic;   
    range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle   =Excel.XlLineStyle.xlContinuous;   
    range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight   =Excel.XlBorderWeight.xlThin;   
        
    if(dt.Columns.Count>1)   
    {   
    range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex   =Excel.XlColorIndex.xlColorIndexAutomatic;   
    range.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle   =   Excel.XlLineStyle.xlContinuous;   
    range.Borders[Excel.XlBordersIndex.xlInsideVertical].Weight   =   Excel.XlBorderWeight.xlThin;   
    }   
        
    if(saveFileName!="")   
    {           
    try   
    {   
    workbook.Saved   =true;         
    workbook.SaveCopyAs(saveFileName);   
    fileSaved=true;   
    }   
    catch(Exception   ex)   
    {   
    fileSaved=false;   
    MessageBox.Show("导出文件时出错,文件可能正被打开!\n"+ex.Message);   
    }   
    }   
    else   
    {   
    fileSaved=false;   
    }         
    xlApp.Quit();         
    GC.Collect();//强行销毁,经测试这句话并没有结束Excel进程
    KillExcelProcess();//强制结束进程
    //用Excel打开文件
    //if(fileSaved&&File.Exists(saveFileName))System.Diagnostics.Process.Start(saveFileName);  
    return fileSaved;
    }
    /// <summary>
    /// 数字转字符。如:1转A 2转B
    /// </summary>
    /// <param name="num">要转换的数字,最大为26,最小为1</param>
    /// <returns></returns>
    private string intToString(int num)
    {
    if (num>26 || num<1)
    {
    return null;
    }
    string[] str = new string[26];
    str[0] = "A";
    str[1] = "B";
    str[2] = "C";
    str[3] = "D";
    str[4] = "E";
    str[5] = "F";
    str[6] = "G";
    str[7] = "H";
    str[8] = "I";
    str[9] = "J";
    str[10] = "K";
    str[11] = "L";
    str[12] = "M";
    str[13] = "N";
    str[14] = "O";
    str[15] = "P";
    str[16] = "Q";
    str[17] = "R";
    str[18] = "S";
    str[19] = "T";
    str[20] = "U";
    str[21] = "V";
    str[22] = "W";
    str[23] = "S";
    str[24] = "Y";
    str[25] = "Z";
    return str[num-1];
    } /// <summary>
    /// 结束Excel进程
    /// </summary>
    private void KillExcelProcess()
    {
    Process[] myProcesses;
    DateTime startTime;
    myProcesses = Process.GetProcessesByName("Excel"); //得不到Excel进程ID,暂时只能判断进程启动时间
    foreach(Process myProcess in myProcesses)
    {
    startTime = myProcess.StartTime; if(startTime > beforeTime && startTime < afterTime)
    {
    myProcess.Kill();
    }
    }
    }
    }
    }