public Form1()
        {
            InitializeComponent();
        }       
        public static DataTable ExcelToDataTable(string strExcelFileName, string strSheetName)
        {
            //源的定义
            string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + strExcelFileName + ";" + "Extended Properties='Excel 12.0;HDR=NO;IMEX=1';";
            string strExcel = "select * from [sheet1$]";            DataSet ds = new DataSet();
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();            //适配到数据源
            OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);
            adapter.Fill(ds, strSheetName);
  
            conn.Close();
            return ds.Tables[strSheetName];
        }        DataTable myT = ExcelToDataTable("D:/lb/lb.xlsx", "sheet1");        int i = 1;
        private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
        {            Brush printcolor = Brushes.Black;
    
            string name= myT.Rows[i][0].ToString();//            e.Graphics.DrawString(name, new Font(new FontFamily("宋体"), 20), printcolor, 200, 205);
            i++;
            e.HasMorePages = true;            if (i >= myT.Rows.Count - 1)
            {
                e.HasMorePages = false;
            }
  
        } private void button1_Click(object sender, EventArgs e)   //打印预览
        {
            //将写好的格式给打印预览控件以便预览
            printPreviewDialog1.Document = printDocument1;            printDocument1.PrintPage += new PrintPageEventHandler(PrintDocument_PrintPage);            printPreviewDialog1.ShowDialog();
        }        private void button2_Click(object sender, EventArgs e)
        {
            printDocument1.PrintPage += new PrintPageEventHandler(PrintDocument_PrintPage);//直接打印
            printDocument1.Print();
        }关闭了打印预览界面之后,再按直接打印就出现如图报错,请问如何解决?

解决方案 »

  1.   

    页计数器 i 没有复位        private void button2_Click(object sender, EventArgs e)
            {
                i = 0;
                printDocument1.PrintPage += new PrintPageEventHandler(PrintDocument_PrintPage);//直接打印
                printDocument1.Print();
            }