茂业's profileDangMY进行式BlogListsGuestbookMore Tools Help

茂业 党

No list items have been added yet.
Welcom to here!

Please wait...
Sorry, the comment you entered is too long. Please shorten it.
You didn't enter anything. Please try again.
Sorry, we can't add your comment right now. Please try again later.
To add a comment, you need permission from your parent. Ask for permission
Your parent has turned off comments.
Sorry, we can't delete your comment right now. Please try again later.
You've exceeded the maximum number of comments that can be left in one day. Please try again in 24 hours.
Your account has had the ability to leave comments disabled because our systems indicate that you may be spamming other users. If you believe that your account has been disabled in error please contact Windows Live support.
Complete the security check below to finish leaving your comment.
The characters you type in the security check must match the characters in the picture or audio.

Windows Media Player

DangMY进行式

沸腾的沉默,喧嚣的平静!

[C#] Web连接Oracle 9.2异常

[问题描述] 当Oracle 9.2运行在NTFS的分区上时,对于某些非administrator组的用户,ORACLE_HOME 目录是不可见的,而在windows server 2003下asp.net应用使用的帐户是netword service,因此无法创建oracle连接,当程序连接时,抛出异常:"System.Data.OracleClient requires Oracle client software version 8.1.7 or greater"
 
[解决步骤] 
1、以管理员的用户登录;
2、找到ORACLE_HOME文件夹(如C:/oracle/ora92),点右键,选属性--安全,在组或用户栏中选“Authenticated Users”,在下面权限列表中把“读取和运行”的权限去掉,再按应用;重新选上“读取和运行”权限,点击应用;选权限框下面的“高级”按钮,确认“Authenticated Users”后面的应用于是“该文件夹、子文件夹及文件”,按确定把权限的更改应用于该文件夹;
3、重新启动计算机,让权限设置生效(请注意,这一步很重要);
4、登录后运行asp.net应用,正常取得Oracle数据库的数据。

[C#] VS2003中实现DataGrid打印类

/// <summary>
/// Purpose:继承PrintDocument,实现DataGrid的打印
/// Author:  Dangmy
/// Date:    2007-03-09
/// Version: 1.0
/// </summary>
public class DataGridPrintDocument:System.Drawing.Printing.PrintDocument
{
    private Font fontCaption = new Font("宋体",12,FontStyle.Bold);   //表名字体
    private Font fontText = new Font("宋体",9);                             //表内容字体
    private int CellSpace = 2;                                                     //单元格与内容空隙
    private SolidBrush brushText = new SolidBrush(Color.Black);       //表格字体笔刷,指定为黑色
    private SolidBrush brushLine = new SolidBrush(Color.Gray);         //表格线条笔刷,指定为灰色
    private SolidBrush brushHead = new SolidBrush(Color.LightGray); //表头背景笔刷,指定为浅灰色
    private SolidBrush brushCell = new SolidBrush(Color.White);        //表格背景笔刷,指定为白色
    private DataGrid dataGrid;                     //打印DataGrid
    private DataTable dataTable;                //打印DataGrid数据表
    private int PageIndex;                          //当前打印的页号
    private int LineCount;                          //每页总共打印行数
    private int ColCount;                            //总共打印的列数
    private int ColIndex;                            //当前打印的列下标
    private int ColLastIndex;                       //上一页打印的列下标
    private int HeaderIndex;                       //当前打印的表头下标
    private int RecordCount;                       //总共打印的记录数
    private int RecordIndex;                        //当前打印记录下标
    private int RecordLastIndex;                  //上一页打印的记录下标
    private float x;                                    //打印X坐标
    private float y;                                    //打印Y坐标
    private bool IsPrintColHeader = false;       //是否每页打印表头
    private bool IsNewPageByCol = false;        //是否换页打印剩余列
    private bool IsNewPageByRow = false;      //是否换页打印剩余行
    private bool IsPreviewed = false;             //是否已生成预览,如果已生成预览,再预览窗口点击打印时,弹出打印机对话框

    private void InitializeComponent()
    {
       
    }

    //构造函数
    public DataGridPrintDocument(DataGrid printDataGrid)
    {
        dataGrid = printDataGrid;
        dataTable = (DataTable)printDataGrid.DataSource;
    }

    //初始化全局变量
    private void InitVar()
    {          
        if(dataTable == null)
            return;
        RecordCount = dataTable.Rows.Count;
        ColCount = dataTable.Columns.Count;
        PageIndex = 1;     
        ColIndex = 0;      
        ColLastIndex = 0;       
        HeaderIndex = 0;       
        RecordIndex = 0;      
        RecordLastIndex = 0;   

}

    protected override void OnBeginPrint(PrintEventArgs e)
    {
        base.OnBeginPrint (e);
        if(IsPreviewed)
        {
            PrintDialog dlgPrint = new PrintDialog();
            dlgPrint.Document = this;
            if(dlgPrint.ShowDialog() != DialogResult.OK)
                e.Cancel = true;
        }   

        InitVar();        
    }


    //PrintDocumen事件重写
    protected override void OnPrintPage(PrintPageEventArgs e)
    {          
        base.OnPrintPage (e);
       
        if(dataTable == null)
            return;

        //计算每页打印行数
        if(DefaultPageSettings.Landscape)
        {
            LineCount = (DefaultPageSettings.PaperSize.Width -
                         DefaultPageSettings.Margins.Left -
                         DefaultPageSettings.Margins.Right -
                         (int)fontCaption.GetHeight(e.Graphics))/
                        ((int)fontText.GetHeight(e.Graphics) + CellSpace + CellSpace);
        }
        else
        {
            LineCount = (DefaultPageSettings.PaperSize.Height -
                         DefaultPageSettings.Margins.Top -
                         DefaultPageSettings.Margins.Bottom -
                         (int)fontCaption.GetHeight(e.Graphics))/
                        ((int)fontText.GetHeight(e.Graphics) + CellSpace + CellSpace);
        }          

        //如果是第一行,则打印表名
        if(PageIndex == 1 && ColIndex == 0)
            DrawCaption(e.Graphics);

        //重置行下标、列下标
        if(IsNewPageByCol)
        {
            RecordIndex = RecordLastIndex;
            ColIndex = ColLastIndex;               
        }          
        if(IsNewPageByRow)
        {
            RecordLastIndex = RecordIndex;
            ColLastIndex = 0;              
        }  
        y = this.DefaultPageSettings.Margins.Top;
       
        //如果是第一页或者每页都打印表头,则打印表头
        if(RecordIndex == 0 || IsPrintColHeader)
            DrawColHeader(e.Graphics);

        //循环打印数据行
        int cnt = 0;
        for( ; RecordIndex<RecordCount; RecordIndex++)
        {
            if( cnt++ == LineCount)
            {
                if(!IsNewPageByCol)
                    IsNewPageByRow = true;
                break;
            }
            if( RecordIndex == RecordCount-1)
            {
                IsNewPageByRow = false;
            }                  
            DrawRow(e.Graphics,RecordIndex);
        }
        ColLastIndex = ColIndex;
       
        //换页
        if(IsNewPageByRow || IsNewPageByCol)
        {
            PageIndex++;
            e.HasMorePages = true;
        }
        IsPreviewed = true;
    }
   
    //打印报表名称
    private void DrawCaption(Graphics g)
    {
        x = this.DefaultPageSettings.Margins.Left;
        y = this.DefaultPageSettings.Margins.Top + fontCaption.GetHeight(g);
        g.DrawString(dataGrid.CaptionText,fontCaption,brushText,x,y);
    }
   
    //打印表头
    private void DrawColHeader(Graphics g)
    {
        x = this.DefaultPageSettings.Margins.Left + CellSpace;
        y += fontCaption.GetHeight(g) + fontText.GetHeight(g) + CellSpace*3;
        Pen penLine = new Pen(brushLine);
        if(!IsNewPageByCol)
            HeaderIndex = 0;
        for( ; HeaderIndex<ColCount; HeaderIndex++ )
        {  
            //超出页宽,停止打印
            if(DefaultPageSettings.Landscape)//横向打印
            {
                if(x > DefaultPageSettings.PaperSize.Height - DefaultPageSettings.Margins.Top - DefaultPageSettings.Margins.Bottom)
                    break;
            }
            else//纵向打印
            {
                if(x > DefaultPageSettings.PaperSize.Width - DefaultPageSettings.Margins.Left - DefaultPageSettings.Margins.Right)
                    break;
            }
            g.FillRectangle(brushHead,x,y,dataGrid.TableStyles[0].GridColumnStyles[HeaderIndex].Width + CellSpace*2,fontText.GetHeight(g) + CellSpace*2);
            g.DrawRectangle(penLine,x,y,dataGrid.TableStyles[0].GridColumnStyles[HeaderIndex].Width + CellSpace*2,fontText.GetHeight(g) + CellSpace*2);
            g.DrawString(dataTable.Columns[HeaderIndex].ToString(), fontText, brushText, x+CellSpace,y+CellSpace);             
            x += dataGrid.TableStyles[0].GridColumnStyles[HeaderIndex].Width + CellSpace;
           
        }
    }

    //打印一行
    private void DrawRow(Graphics g,int index)
    {
        x = this.DefaultPageSettings.Margins.Left + CellSpace;
        y += fontText.GetHeight(g) + CellSpace;
        Pen penLine = new Pen(brushLine);
       
        for(ColIndex = ColLastIndex; ColIndex<ColCount; ColIndex++ )
        {  
            //超出页宽,停止打印
            if(DefaultPageSettings.Landscape)//横向打印
            {
                if(x > DefaultPageSettings.PaperSize.Height - DefaultPageSettings.Margins.Top  - DefaultPageSettings.Margins.Bottom)
                {
                    IsNewPageByCol = true;

                    IsNewPageByRow = false;
                    break;
                }
            }
            else//纵向打印
            {
                if( x > DefaultPageSettings.PaperSize.Width - DefaultPageSettings.Margins.Left - DefaultPageSettings.Margins.Right)
                {
                    IsNewPageByCol = true;

                    IsNewPageByRow = false;
                    break;
                }
            }      
            g.FillRectangle(brushCell,x,y,dataGrid.TableStyles[0].GridColumnStyles[ColIndex].Width + CellSpace*2,fontText.GetHeight(g) + CellSpace*2);
            g.DrawRectangle(penLine,x,y,dataGrid.TableStyles[0].GridColumnStyles[ColIndex].Width + CellSpace*2,fontText.GetHeight(g) + CellSpace*2);
            g.DrawString(dataTable.Rows[index][ColIndex].ToString(), fontText, brushText, x + CellSpace,y + CellSpace);
            x += dataGrid.TableStyles[0].GridColumnStyles[ColIndex].Width + CellSpace; 
        }
        if(ColIndex == ColCount)
            IsNewPageByCol = false;
    }

}

 //打印预览调用
  private void btnPrint_Click(object sender, System.EventArgs e)
  {   
      DataGridPrintDocument printDocument = new DataGridPrintDocument(dataGrid1);  
      //页面设置
      PageSetupDialog dlgPage = new PageSetupDialog();
      dlgPage.Document = printDocument;
      dlgPage.ShowDialog();
      //预览
      PrintPreviewDialog dlgPreview = new PrintPreviewDialog();
      dlgPreview.Document = printDocument;
      dlgPreview.ShowDialog(); 
  }

 

[C#] DataGrid根据实际内容调整列宽

   //自动调整DataGrid列宽
    public static void AutoSizeGrid(DataGrid dataGrid)
    {
        DataGridTableStyle tableStyle = new DataGridTableStyle();          
        System.Windows.Forms.DataGridTextBoxColumn colStyle;
        DataTable dt = (DataTable)dataGrid.DataSource;     
       
        //循环列
        for(int col=0; col<dt.Columns.Count; col++)
        {
            float width = 0;
            Graphics g = Graphics.FromHwnd(dataGrid.Handle);
            StringFormat sf = new StringFormat(StringFormat.GenericTypographic);
            SizeF size = new SizeF();
            //循环行,得到最大宽度
            for(int row=0; row<dt.Rows.Count; row++)
            {
                size = g.MeasureString(dataGrid[row,col].ToString(),dataGrid.Font,500,sf);
                if(size.Width > width)
                    width = size.Width;
            }
            g.Dispose();
           
            if(width < dataGrid.PreferredColumnWidth)
                width = dataGrid.PreferredColumnWidth;

            if(dataGrid.TableStyles.Count > 0)
                dataGrid.TableStyles[0].GridColumnStyles[col].Width = (int)width + 10;
            else
            {                  
                colStyle = new DataGridTextBoxColumn();
                colStyle.MappingName = dt.Columns[col].Caption;
                colStyle.HeaderText = dt.Columns[col].Caption;
                colStyle.Width = (int)width + 10;
                tableStyle.GridColumnStyles.Add(colStyle);
            }  
        }
        if(dataGrid.TableStyles.Count == 0)
        {
            tableStyle.RowHeadersVisible = false;
            dataGrid.TableStyles.Add(tableStyle);
        }
    }

[C#] EXCEL导入导出类

///////////////////////////////////////////////////////////////////////////
//Purpose:Excel文件导入导出,需引用Microsoft Excel 11.0 Object Library
//Author: Dangmy
//Date: 2007-03-09
//Version: 1.0
///////////////////////////////////////////////////////////////////////////

public class ExcelIO
{
    private int _ReturnStatus;
    private string _ReturnMessage;

    /// <summary>
    /// 执行返回状态
    /// </summary>
    public int ReturnStatus
    {
        get{return _ReturnStatus;}
    }

    /// <summary>
    /// 执行返回信息
    /// </summary>
    public string ReturnMessage
    {
        get{return _ReturnMessage;}
    }

    public ExcelIO()
    {
    }

    /// <summary>
    /// 导入EXCEL到DataSet
    /// </summary>
    /// <param name="fileName">Excel全路径文件名</param>
    /// <returns>导入成功的DataSet</returns>
    public DataSet ImportExcel(string fileName)
    {
        //判断是否安装EXCEL
        Excel.Application xlApp=new Excel.ApplicationClass();          
        if(xlApp==null)
        {
            _ReturnStatus = -1;
            _ReturnMessage = "无法创建Excel对象,可能您的计算机未安装Excel";
            return null;
        }      

        //判断文件是否被其他进程使用           
        Excel.Workbook workbook;               
        try
        {
            workbook = xlApp.Workbooks.Open(fileName,0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, 1, 0);
        }
        catch
        {
            _ReturnStatus = -1;
            _ReturnMessage = "Excel文件处于打开状态,请保存关闭";
            return null;
        }      
       
        //获得所有Sheet名称
        int n = workbook.Worksheets.Count;
        string[] SheetSet = new string[n];
        System.Collections.ArrayList al = new System.Collections.ArrayList();
        for(int i=1; i<=n; i++)
        {
            SheetSet[i-1] = ((Excel.Worksheet)workbook.Worksheets[i]).Name;
        }
       
        //释放Excel相关对象
        workbook.Close(null,null,null);        
        xlApp.Quit();
        if(workbook != null)
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
            workbook = null;
        }
        if(xlApp != null)
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
            xlApp = null;
        }  
        GC.Collect();
       
        //把EXCEL导入到DataSet
        DataSet ds = new DataSet();        
        string connStr = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = "+ fileName +";Extended Properties=Excel 8.0" ;
        using(OleDbConnection conn = new OleDbConnection (connStr))
        {
            conn.Open();
            OleDbDataAdapter da;
            for(int i=1; i<=n; i++)
            {
                string sql = "select * from ["+ SheetSet[i-1] +"$] ";
                da = new OleDbDataAdapter(sql,conn);
                da.Fill(ds,SheetSet[i-1]); 
                da.Dispose();
            }              
            conn.Close();
            conn.Dispose();
        }              
        return ds;
    }

    /// <summary>
    /// 把DataTable导出到EXCEL
    /// </summary>
    /// <param name="reportName">报表名称</param>
    /// <param name="dt">数据源表</param>
    /// <param name="saveFileName">Excel全路径文件名</param>
    /// <returns>导出是否成功</returns>
    public bool ExportExcel(string reportName,DataTable dt,string saveFileName)
    {
        if(dt==null)
        {
            _ReturnStatus = -1;
            _ReturnMessage = "数据集为空!";
            return false;          
        }

        bool fileSaved=false;
        Excel.Application xlApp=new Excel.ApplicationClass();  
        if(xlApp==null)
        {
            _ReturnStatus = -1;
            _ReturnMessage = "无法创建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
        worksheet.Cells.Font.Size = 10;
        Excel.Range range;

        long totalCount=dt.Rows.Count;
        long rowRead=0;
        float percent=0;

        worksheet.Cells[1,1]=reportName;
        ((Excel.Range)worksheet.Cells[1,1]).Font.Size = 12;
        ((Excel.Range)worksheet.Cells[1,1]).Font.Bold = true;

        //写入字段
        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.Interior.ColorIndex = 15;
            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].ToString();
            }
            rowRead++;
            percent=((float)(100*rowRead))/totalCount;
        }
       
        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);
        if( dt.Rows.Count > 0)
        {
            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;
                _ReturnStatus = -1;
                _ReturnMessage = "导出文件时出错,文件可能正被打开!\n"+ex.Message;
            }
        }
        else
        {
            fileSaved=false;
        }          
   
        //释放Excel对应的对象
        if(range != null)
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
            range = null;
        }
        if(worksheet != null)
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
            worksheet = null;
        }
        if(workbook != null)
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
            workbook = null;
        }
        if(workbooks != null)
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
            workbooks = null;
        }              
        xlApp.Application.Workbooks.Close();
        xlApp.Quit();
        if(xlApp != null)
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
            xlApp = null;
        }
        GC.Collect();
        return fileSaved;
    }
}

PL/SQL与TSQL游标用法比较

1. PL/SQL举例
   DECLARE
     var_id    tab.id%TYPE;
     var_name  tab.name%TYPE;
     cursor test_cursor is
       select id,name
       from tab;
   BEGIN
      OPEN test_cursor
      LOOP
          FETCH test_cursor INTO _id, name;
          EXIT WHEN test_cursor %NOTFOUND;
          ...
      END LOOP;
      CLOSE test_cursor
   END
  
   动态游标: open test_cursor for "select id,name from tab";
 
   [游标参数]
   %ROWCOUNT: number of rows affected by last SQL statement
   %FOUND   : TRUE if >1 row returned
   %NOTFOUND: bool - TRUE if 0 rows returned
   %ISOPEN  : bool - TRUE if cursor still open
 
2. TSQL举例
   DECLARE @var_id integer
   DECLARE @var_name varchar(40)
   DECLARE test_cursor CURSOR FOR
           select id,name
           from tab;   
   OPEN test_cursor
   FETCH NEXT FROM test_cursor
   INTO @var_id, @var_name
 
   WHILE @@FETCH_STATUS = 0
   BEGIN
       FETCH NEXT FROM test_cursor
       INTO @var_id, @var_name
       ...
   END
   CLOSE test_cursor
   DEALLOCATE test_cursor
  
   [游标参数]
   @@CURSOR_ROWS: 返回连接上最后打开的游标中当前存在的合格行的数量
   @@FETCH_STATUS: 返回被 FETCH 语句执行的最后游标的状态,而不是任何当前被连接打开的游标的状态。
   CURSOR_STATUS(..): 针对一个给定参数,确定该过程是否返回游标和结果集