示例#1
0
 public Frm_Print_Set(PrintModel modes, string TableName)
 {
     InitializeComponent();
     model          = modes;
     PrintTableName = TableName;
     tableName      = modes.Printtable.TableName.ToString();
 }
示例#2
0
 public Frm_Print_Set(PrintModel modes, string TableName)
 {
     InitializeComponent();
     model = modes;
     PrintTableName = TableName;
     tableName = modes.Printtable.TableName.ToString();
 }
示例#3
0
 public static void PrintSet(System.Windows.Forms.DataGridView dgv, string title, string strSum)
 {
     if (dgv.DataSource == null)
     {
         MessageBox.Show("没有数据,无法选择输出格式", "提示");
         return;
     }
     model = GetModel.getMode(dgv, title, strSum);//获得打印参数
     Frm_Print_Set cs = new Frm_Print_Set(model, title);
     cs.ShowDialog();
 }
示例#4
0
 public static void Print(System.Windows.Forms.DataGridView dgv, string title, string strSum)
 {
     if (dgv.DataSource == null)
     {
         MessageBox.Show("没有数据,无法打印", "提示");
         return;
     }
     model = GetModel.getMode(dgv, title, strSum);//获得打印参数
     FormPrint print = new FormPrint(model);
     print.CallPrintForm(dgv, title, strSum);
 }
示例#5
0
 public static void PrintSet128(DataGridViewKJ128 dgv, string title, string strSum)
 {
     if (dgv.DataSource == null)
     {
         MessageBox.Show("没有数据,无法选择输出格式", "提示");
         return;
     }
     DataGridView dgvs = dgv;
     model = GetModel.getMode(dgvs, title, strSum);//获得打印参数
     Frm_Print_Set cs = new Frm_Print_Set(model, title);
     cs.ShowDialog();
 }
示例#6
0
 public static void Print(DataGridViewKJ128 dgv,string title)
 {
     if (dgv.DataSource == null)
     {
         MessageBox.Show("没有数据,无法打印", "提示");
         return;
     }
     DataGridView dgvs = dgv;
     model = GetModel.getMode(dgvs, title, "");//获得打印参数
     FormPrint print = new FormPrint(model);
     print.CallPrintForm(dgv, title, "");
 }
示例#7
0
        public static void GetDataTable(PrintModel model, DataGridView dgv)
        {
            List <string> strColumns    = new List <string>();
            List <string> strHeaderText = new List <string>();
            DataTable     DtTemp        = null;

            try
            {
                DtTemp = (dgv.DataSource as DataTable).Copy();
                //删除隐藏的datatcolumn列
                foreach (DataGridViewColumn col in dgv.Columns)
                {
                    if (col.Visible == false)//|| col.GetType().ToString() == "System.Windows.Forms.DataGridViewCheckBoxColumn"
                    {
                        if (DtTemp.Columns.Contains(col.Name))
                        {
                            DtTemp.Columns.Remove(col.Name);
                        }
                    }
                }

                for (int i = 0; i < dgv.Columns.Count; i++)
                {
                    strColumns.Add("");
                    strHeaderText.Add("");
                }

                for (int i = 0; i < dgv.Columns.Count; i++)
                {
                    if (dgv.Columns[i].Visible == true)
                    {
                        strColumns[dgv.Columns[i].DisplayIndex]    = dgv.Columns[i].Name.ToString();
                        strHeaderText[dgv.Columns[i].DisplayIndex] = dgv.Columns[i].HeaderText.ToString();
                    }
                }
                while (strColumns.Contains(""))
                {
                    strColumns.Remove("");
                    strHeaderText.Remove("");
                }

                //根据保存的模板设置列顺序
                if (model.Columns.Count != 0 && DtTemp.TableName != "Table" && DtTemp.TableName != "A_InitialData")
                {
                    //设置datatable列索引
                    //string[] tempStr = model.Columns.Split(',');
                    for (int i = 0; i < model.Columns.Count; i++)
                    {
                        DtTemp.Columns[model.Columns[i].ToString()].SetOrdinal(i);
                    }
                }
                else
                {
                    //根据displayindex设置列顺序
                    for (int i = 0; i < strColumns.Count; i++)
                    {
                        DtTemp.Columns[strColumns[i]].SetOrdinal(i);
                    }
                }
                if (strColumns.Count != 0 && strColumns.Count != 0)
                {
                    model.Columnname = strColumns;
                    model.Columntext = strHeaderText;
                }
            }
            catch (Exception ee)
            {
                if (DtTemp == null)
                {
                    if (!ee.Message.Equals("正在中止线程。"))
                    {
                        MessageBox.Show("由于系统错误导出任务未执行", "提示");
                    }
                    return;
                }
            }
            model.Printtable = DtTemp;
        }
示例#8
0
        /// <summary>
        /// 获取Model
        /// </summary>
        /// <param name="Grid"></param>
        /// <param name="PrintName"></param>
        /// <param name="TjTime"></param>
        /// <returns></returns>
        public static PrintModel getMode(DataGridView Grid, string PrintName, string TjTime)
        {
            PrintModel model = new PrintModel();

            #region [加载打印基础配置信息]
            //if (TjTime.ToString().Contains("统计时间"))
            //{
            //    model.Tjtime = Grid.;
            //}
            //else
            //{
            //    model.Tjtime = "";
            //}
            model.Tjtime = "共 " + Grid.Rows.Count + " 条记录";
            string tableName = string.Empty;

            tableName = (Grid.DataSource as DataTable).TableName.ToString();
            if (!Directory.Exists(Application.StartupPath.ToString() + "\\PrintSetModel"))
            {
                Directory.CreateDirectory(Application.StartupPath.ToString() + "\\PrintSetModel");
            }
            if (!File.Exists(Application.StartupPath.ToString() + "\\PrintSetModel\\" + tableName + ".xml"))
            {
                FileStream   fs = new FileStream(Application.StartupPath.ToString() + "\\PrintSetModel\\" + tableName + ".xml", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamWriter ws = new StreamWriter(fs);
                ws.WriteLine("<PrintSet>");
                ws.WriteLine("<TableName></TableName>");
                ws.WriteLine("<Font>");
                ws.WriteLine("<TitleFont>宋体,21.75,Center</TitleFont>");
                ws.WriteLine("<subTitleFont>宋体,7.5,Center</subTitleFont>");
                ws.WriteLine("<ContentFont>宋体,7.5,Center</ContentFont>");
                ws.WriteLine("<SignFont>宋体,10.5,Center</SignFont>");
                ws.WriteLine("</Font>");
                ws.WriteLine("<PageSet>");
                ws.WriteLine("<PageSize>21,29.7</PageSize>");     //cm
                ws.WriteLine("<Margin>0.5,0.5,0.5,0.5</Margin>"); //cm
                ws.WriteLine("</PageSet>");
                ws.WriteLine("<Sign>");
                ws.WriteLine("<LeaderList>制表人,,,</LeaderList>");
                ws.WriteLine("</Sign>");
                ws.WriteLine("<Content>");
                ws.WriteLine("<Columns></Columns>");
                ws.WriteLine("<Width></Width>");
                ws.WriteLine("</Content>");
                ws.WriteLine("</PrintSet>");
                ws.Close();
                ws.Dispose();
                fs.Close();
                fs.Dispose();
            }
            XmlDocument doc = new XmlDocument();
            doc.Load(Application.StartupPath.ToString() + "\\PrintSetModel\\" + tableName + ".xml");
            //表格名称

            model.Printname = doc.SelectSingleNode("/PrintSet/TableName").InnerText.ToString();
            if (model.Printname == "")
            {
                model.Printname = PrintName;
            }
            //标题栏字体
            string[] Temp = doc.SelectSingleNode("/PrintSet/Font/TitleFont").InnerText.ToString().Trim().Split(',');
            model.Titlefontfamily = Temp[0].ToString();
            model.Titlefontsize   = (float)(Convert.ToDouble(Temp[1].ToString()));
            model.Titlefontstyle  = Temp[2].ToString();

            //副标题字体
            Temp = doc.SelectSingleNode("/PrintSet/Font/subTitleFont").InnerText.ToString().Trim().Split(',');
            model.Subfontfamily = Temp[0].ToString();
            model.Subfontsize   = (float)(Convert.ToDouble(Temp[1].ToString()));
            model.Subfontstyle  = Temp[2].ToString();

            //表格字体
            Temp = doc.SelectSingleNode("/PrintSet/Font/ContentFont").InnerText.ToString().Trim().Split(',');
            model.Contentfontfamily = Temp[0].ToString();
            model.Contentfontsize   = (float)(Convert.ToDouble(Temp[1].ToString()));
            model.Contentfontstyle  = Temp[2].ToString();

            //签名栏字体
            Temp = doc.SelectSingleNode("/PrintSet/Font/SignFont").InnerText.ToString().Trim().Split(',');
            model.Signfontfamily = Temp[0].ToString();
            model.Signfontsize   = (float)(Convert.ToDouble(Temp[1].ToString()));
            model.Signfontstyle  = Temp[2].ToString();

            //纸张大小
            Temp              = doc.SelectSingleNode("/PrintSet/PageSet/PageSize").InnerText.ToString().Trim().Split(',');
            model.Paperwidth  = Temp[0].ToString();
            model.Paperheight = Temp[1].ToString();

            //纸张边距
            Temp              = doc.SelectSingleNode("/PrintSet/PageSet/Margin").InnerText.ToString().Trim().Split(',');
            model.Papertop    = Temp[0].ToString();
            model.Paperbottom = Temp[1].ToString();
            model.Paperleft   = Temp[2].ToString();
            model.Paperright  = Temp[3].ToString();

            //签名栏内容
            model.Signcontent = doc.SelectSingleNode("/PrintSet/Sign/LeaderList").InnerText.ToString().Trim();

            //表格选择的列名集合
            string temp = doc.SelectSingleNode("/PrintSet/Content/Columns").InnerText.ToString().Trim();
            if (temp != "")
            {
                foreach (string strTemp in temp.Split(','))
                {
                    model.Columns.Add(strTemp);
                }
            }

            //表格选择的列宽集合
            temp = doc.SelectSingleNode("/PrintSet/Content/Width").InnerText.ToString().Trim();
            if (temp != "")
            {
                foreach (string strTemp in temp.Split(','))
                {
                    model.Columnswidth.Add(strTemp);
                }
            }
            #endregion

            //加工成有效的数据源
            GetDataTable(model, Grid);

            return(model);
        }
示例#9
0
        //导出线程
        private void Export()
        {
            try
            {
                model = GetModel.getMode(dgvs, ttName, tjTime);//获取导出数据的模型

                //删除大于模板的列
                if (model.Columns.Count != 0 && model.Printtable.TableName != "A_InitialData")
                {
                    //判断一个string是否在string[]中
                    List<string> lst = model.Columns;

                    for (int j = 0; j < model.Printtable.Columns.Count; j++)
                    {
                        if (!lst.Contains(model.Printtable.Columns[j].ColumnName.ToString()))
                        {
                            model.Printtable.Columns.Remove(model.Printtable.Columns[j].ColumnName);
                            j--;
                        }

                    }
                }

                object objOpt = Missing.Value;

                try
                {
                    excel = new Microsoft.Office.Interop.Excel.Application();
                }
                catch(Exception ee)
                {
                    if (!ee.Message.Equals("正在中止线程。"))
                    {
                        MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
                    }
                    //string time = System.DateTime.Now.ToShortDateString() + " " + System.DateTime.Now.ToLongTimeString();
                    //myop.addOper(time, "无法创建Excel对象,可能您的机子未安装Excel", "NO");
                    return;
                }

                excel.Visible = false;
                wkb = excel.Workbooks.Add(objOpt);
                _Worksheet wks = (_Worksheet)wkb.ActiveSheet;
                wks.Visible = XlSheetVisibility.xlSheetVisible;

                int rowIndex = 1;
                int colIndex = 1;
                int x = 0;
                int y = 0;
                System.Data.DataTable table = ProcessDataTable(model.Printtable);
               

                #region[标题栏]
                //标题栏
                var RowAll1 = wks.get_Range(wks.Cells[rowIndex, 1], wks.Cells[rowIndex, table.Columns.Count]);
                RowAll1.Merge(0);
                excel.Cells[rowIndex, 1] = model.Printname;
                RowAll1.Font.Size = model.Titlefontsize;
                RowAll1.Font.FontStyle = FontStyle.Bold;
                RowAll1.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                rowIndex++;
                #endregion

                #region[副标题信息]

                //统计时间
                var RowAll2 = wks.get_Range(wks.Cells[rowIndex, 1], wks.Cells[rowIndex, table.Columns.Count / 2]);
                RowAll2.Merge(0);
                excel.Cells[rowIndex, 1] = "打印时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                RowAll2.Font.Size = model.Subfontsize;
                RowAll2.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;

                var RowAll3 = wks.get_Range(wks.Cells[rowIndex, table.Columns.Count / 2 + 1], wks.Cells[rowIndex, table.Columns.Count]);
                RowAll3.Merge(0);
                excel.Cells[rowIndex, table.Columns.Count / 2 + 1] = model.Tjtime;
                RowAll3.Font.Size = model.Subfontsize;
                RowAll3.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignRight;
                rowIndex++;
                #endregion

                #region[主体信息]
                x = rowIndex;
                foreach (DataColumn col in table.Columns)
                {

                    excel.Cells[x, colIndex] = dgvs.Columns[col.ColumnName].HeaderText;
                    excel.Columns.NumberFormatLocal = "@";
                    colIndex++;
                }
                //foreach (DataRow row in table.Rows)
                //{
                //    rowIndex++;
                //    colIndex = 0;

                //    foreach (DataColumn col in table.Columns)
                //    {
                //        try
                //        {
                //            colIndex++;
                //            // excel.Cells[rowIndex, colIndex] = "1";
                //            excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
                //        }
                //        catch (Exception ex)
                //        {

                //        }
                //        //excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
                //    }
                //}
                int rowCount = table.Rows.Count;

                int colCount = table.Columns.Count;

                object[,] dataArray = new object[rowCount, colCount];

                for (int i = 0; i < rowCount; i++)
                {
                    for (int j = 0; j < colCount; j++)
                    {
                        dataArray[i, j] = table.Rows[i][j].ToString();
                    }

                }
                try
                {
                    wks.get_Range("A4", wks.Cells[rowCount + 3, colCount]).Value2 = dataArray;
                }
                catch(Exception ee)
                {
                    if (!ee.Message.Equals("正在中止线程。"))
                    {
                        MessageBox.Show("Excel2003最多只支持65536行数据导出,请重新选择导出数据", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    try
                    {
                        wkb.Close(false, objOpt, objOpt);
                        excel.Quit();
                        if (this.IsHandleCreated)
                            this.Invoke(new MethodInvoker(delegate()
                            {
                                this.Close();
                            }));
                    }
                    catch { }
                }

                y = rowIndex;
                var RowAll = wks.get_Range("A3", wks.Cells[rowCount + 3, colCount]);
                    //wks.get_Range(wks.Cells[x, 1], wks.Cells[y, table.Columns.Count]);
                RowAll.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                RowAll.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                RowAll.EntireColumn.AutoFit();//列宽自适应
                rowIndex = 4 + rowCount;
                #endregion

                #region[签名栏]
                if (table.Columns.Count >= 4)
                {
                    var RowAll4 = wks.get_Range(wks.Cells[rowIndex, 1], wks.Cells[rowIndex, (table.Columns.Count / 4) > 0 ? (table.Columns.Count / 4) : 1]);
                    RowAll4.Merge(0);
                    excel.Cells[rowIndex, 1] = model.Signcontent.Split(',')[0].ToString();
                    RowAll4.Font.Size = model.Signfontsize;
                    RowAll4.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

                    var RowAll5 = wks.get_Range(wks.Cells[rowIndex, table.Columns.Count / 4 + 1], wks.Cells[rowIndex, (table.Columns.Count / 2) > 0 ? (table.Columns.Count / 2) : 1]);
                    RowAll5.Merge(0);
                    excel.Cells[rowIndex, table.Columns.Count / 4 + 1] = model.Signcontent.Split(',')[1].ToString();
                    RowAll5.Font.Size = model.Signfontsize;
                    RowAll5.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

                    var RowAll6 = wks.get_Range(wks.Cells[rowIndex, table.Columns.Count / 2 + 1], wks.Cells[rowIndex, (table.Columns.Count * 3 / 4) > 0 ? (table.Columns.Count * 3 / 4) : 1]);
                    RowAll6.Merge(0);
                    excel.Cells[rowIndex, table.Columns.Count / 2 + 1] = model.Signcontent.Split(',')[2].ToString();
                    RowAll6.Font.Size = model.Signfontsize;
                    RowAll6.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

                    var RowAll7 = wks.get_Range(wks.Cells[rowIndex, table.Columns.Count * 3 / 4 + 1], wks.Cells[rowIndex, table.Columns.Count]);
                    RowAll7.Merge(0);
                    excel.Cells[rowIndex, table.Columns.Count * 3 / 4 + 1] = model.Signcontent.Split(',')[3].ToString();
                    RowAll7.Font.Size = model.Signfontsize;
                    RowAll7.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                }
                else
                {
                    var RowAll8 = wks.get_Range(wks.Cells[rowIndex, 1], wks.Cells[rowIndex, table.Columns.Count]);
                    RowAll8.Merge(0);
                    string s = string.Empty;
                    foreach (string str in model.Signcontent.Split(','))
                    {
                        s += str + "  ";
                    }
                    excel.Cells[rowIndex, 1] = s;
                    RowAll8.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                }
                #endregion

                #region[获得父窗体句柄]
                System.IntPtr IntPart;
                IntPart = GetForegroundWindow();
                WindowWrapper ParentFrm = new WindowWrapper(IntPart);
                #endregion

                #region[导出对话框]
                string excelFileName = string.Empty;
                SaveFileDialog sf = new SaveFileDialog();
                sf.Filter = "*.xls|*.*";
                if (sf.ShowDialog(ParentFrm) == DialogResult.OK)
                {
                    try
                    {
                        excelFileName = sf.FileName;
                        wkb.SaveAs(excelFileName, objOpt, null, null, false, false, XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);
                        wkb.Close(false, objOpt, objOpt);
                        excel.Quit();
                        excel = null;
                        if (this.IsHandleCreated)
                            this.Invoke(new MethodInvoker(delegate()
                            {
                                label1.Text = "导出成功!";
                                label1.Left = (this.Width - label1.Width) / 2;
                                btn_Export.Text = "确定";
                                btn_Export.Click -= new EventHandler(btn_Export_Click);
                                btn_Export.Click += new EventHandler(btn_Export_Exit);
                                pictureBox2.Visible = false;
                                lblExport.Visible = false;
                            }));

                        //MessageBox.Show("导出成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch
                    {
                        wkb.Close(false, objOpt, objOpt);
                        excel.Quit();
                        if (this.IsHandleCreated)
                            this.Invoke(new MethodInvoker(delegate()
                            {
                                this.Close();
                            }));
                    }
                }
                else
                {
                    wkb.Close(false, objOpt, objOpt);
                    excel.Quit();
                    if (this.IsHandleCreated)
                        this.Invoke(new MethodInvoker(delegate()
                        {
                            this.Close();
                        }));
                }
                #endregion
            }
            catch (Exception ee)
            {
                if (!ee.Message.ToString().Equals("正在中止线程。"))
                    MessageBox.Show("Excel导出失败[" + ee.Message + "][" + ee.StackTrace + "]");
            }
           
        }
示例#10
0
 public FormPrint(PrintModel model)
 {
     InitializeComponent();
     Model = model;
 }
示例#11
0
        //导出线程
        private void Export()
        {
            try
            {
                model = GetModel.getMode(dgvs, ttName, tjTime);//获取导出数据的模型

                //删除大于模板的列
                if (model.Columns.Count != 0 && model.Printtable.TableName != "A_InitialData")
                {
                    //判断一个string是否在string[]中
                    List <string> lst = model.Columns;

                    for (int j = 0; j < model.Printtable.Columns.Count; j++)
                    {
                        if (!lst.Contains(model.Printtable.Columns[j].ColumnName.ToString()))
                        {
                            model.Printtable.Columns.Remove(model.Printtable.Columns[j].ColumnName);
                            j--;
                        }
                    }
                }

                object objOpt = Missing.Value;

                try
                {
                    excel = new Microsoft.Office.Interop.Excel.Application();
                }
                catch (Exception ee)
                {
                    if (!ee.Message.Equals("正在中止线程。"))
                    {
                        MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
                    }
                    //string time = System.DateTime.Now.ToShortDateString() + " " + System.DateTime.Now.ToLongTimeString();
                    //myop.addOper(time, "无法创建Excel对象,可能您的机子未安装Excel", "NO");
                    return;
                }

                excel.Visible = false;
                wkb           = excel.Workbooks.Add(objOpt);
                _Worksheet wks = (_Worksheet)wkb.ActiveSheet;
                wks.Visible = XlSheetVisibility.xlSheetVisible;

                int rowIndex = 1;
                int colIndex = 1;
                int x        = 0;
                int y        = 0;
                System.Data.DataTable table = ProcessDataTable(model.Printtable);


                #region [标题栏]
                //标题栏
                var RowAll1 = wks.get_Range(wks.Cells[rowIndex, 1], wks.Cells[rowIndex, table.Columns.Count]);
                RowAll1.Merge(0);
                excel.Cells[rowIndex, 1]    = model.Printname;
                RowAll1.Font.Size           = model.Titlefontsize;
                RowAll1.Font.FontStyle      = FontStyle.Bold;
                RowAll1.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                rowIndex++;
                #endregion

                #region [副标题信息]

                //统计时间
                var RowAll2 = wks.get_Range(wks.Cells[rowIndex, 1], wks.Cells[rowIndex, table.Columns.Count / 2]);
                RowAll2.Merge(0);
                excel.Cells[rowIndex, 1]    = "打印时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                RowAll2.Font.Size           = model.Subfontsize;
                RowAll2.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;

                var RowAll3 = wks.get_Range(wks.Cells[rowIndex, table.Columns.Count / 2 + 1], wks.Cells[rowIndex, table.Columns.Count]);
                RowAll3.Merge(0);
                excel.Cells[rowIndex, table.Columns.Count / 2 + 1] = model.Tjtime;
                RowAll3.Font.Size           = model.Subfontsize;
                RowAll3.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignRight;
                rowIndex++;
                #endregion

                #region [主体信息]
                x = rowIndex;
                foreach (DataColumn col in table.Columns)
                {
                    excel.Cells[x, colIndex]        = dgvs.Columns[col.ColumnName].HeaderText;
                    excel.Columns.NumberFormatLocal = "@";
                    colIndex++;
                }
                //foreach (DataRow row in table.Rows)
                //{
                //    rowIndex++;
                //    colIndex = 0;

                //    foreach (DataColumn col in table.Columns)
                //    {
                //        try
                //        {
                //            colIndex++;
                //            // excel.Cells[rowIndex, colIndex] = "1";
                //            excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
                //        }
                //        catch (Exception ex)
                //        {

                //        }
                //        //excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
                //    }
                //}
                int rowCount = table.Rows.Count;

                int colCount = table.Columns.Count;

                object[,] dataArray = new object[rowCount, colCount];

                for (int i = 0; i < rowCount; i++)
                {
                    for (int j = 0; j < colCount; j++)
                    {
                        dataArray[i, j] = table.Rows[i][j].ToString();
                    }
                }
                try
                {
                    wks.get_Range("A4", wks.Cells[rowCount + 3, colCount]).Value2 = dataArray;
                }
                catch (Exception ee)
                {
                    if (!ee.Message.Equals("正在中止线程。"))
                    {
                        MessageBox.Show("Excel2003最多只支持65536行数据导出,请重新选择导出数据", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    try
                    {
                        wkb.Close(false, objOpt, objOpt);
                        excel.Quit();
                        if (this.IsHandleCreated)
                        {
                            this.Invoke(new MethodInvoker(delegate()
                            {
                                this.Close();
                            }));
                        }
                    }
                    catch { }
                }

                y = rowIndex;
                var RowAll = wks.get_Range("A3", wks.Cells[rowCount + 3, colCount]);
                //wks.get_Range(wks.Cells[x, 1], wks.Cells[y, table.Columns.Count]);
                RowAll.Borders.LineStyle   = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                RowAll.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                RowAll.EntireColumn.AutoFit();//列宽自适应
                rowIndex = 4 + rowCount;
                #endregion

                #region [签名栏]
                if (table.Columns.Count >= 4)
                {
                    var RowAll4 = wks.get_Range(wks.Cells[rowIndex, 1], wks.Cells[rowIndex, (table.Columns.Count / 4) > 0 ? (table.Columns.Count / 4) : 1]);
                    RowAll4.Merge(0);
                    excel.Cells[rowIndex, 1]    = model.Signcontent.Split(',')[0].ToString();
                    RowAll4.Font.Size           = model.Signfontsize;
                    RowAll4.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

                    var RowAll5 = wks.get_Range(wks.Cells[rowIndex, table.Columns.Count / 4 + 1], wks.Cells[rowIndex, (table.Columns.Count / 2) > 0 ? (table.Columns.Count / 2) : 1]);
                    RowAll5.Merge(0);
                    excel.Cells[rowIndex, table.Columns.Count / 4 + 1] = model.Signcontent.Split(',')[1].ToString();
                    RowAll5.Font.Size           = model.Signfontsize;
                    RowAll5.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

                    var RowAll6 = wks.get_Range(wks.Cells[rowIndex, table.Columns.Count / 2 + 1], wks.Cells[rowIndex, (table.Columns.Count * 3 / 4) > 0 ? (table.Columns.Count * 3 / 4) : 1]);
                    RowAll6.Merge(0);
                    excel.Cells[rowIndex, table.Columns.Count / 2 + 1] = model.Signcontent.Split(',')[2].ToString();
                    RowAll6.Font.Size           = model.Signfontsize;
                    RowAll6.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

                    var RowAll7 = wks.get_Range(wks.Cells[rowIndex, table.Columns.Count * 3 / 4 + 1], wks.Cells[rowIndex, table.Columns.Count]);
                    RowAll7.Merge(0);
                    excel.Cells[rowIndex, table.Columns.Count * 3 / 4 + 1] = model.Signcontent.Split(',')[3].ToString();
                    RowAll7.Font.Size           = model.Signfontsize;
                    RowAll7.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                }
                else
                {
                    var RowAll8 = wks.get_Range(wks.Cells[rowIndex, 1], wks.Cells[rowIndex, table.Columns.Count]);
                    RowAll8.Merge(0);
                    string s = string.Empty;
                    foreach (string str in model.Signcontent.Split(','))
                    {
                        s += str + "  ";
                    }
                    excel.Cells[rowIndex, 1]    = s;
                    RowAll8.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                }
                #endregion

                #region [获得父窗体句柄]
                System.IntPtr IntPart;
                IntPart = GetForegroundWindow();
                WindowWrapper ParentFrm = new WindowWrapper(IntPart);
                #endregion

                #region [导出对话框]
                string         excelFileName = string.Empty;
                SaveFileDialog sf            = new SaveFileDialog();
                sf.Filter = "*.xls|*.*";
                if (sf.ShowDialog(ParentFrm) == DialogResult.OK)
                {
                    try
                    {
                        excelFileName = sf.FileName;
                        wkb.SaveAs(excelFileName, objOpt, null, null, false, false, XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);
                        wkb.Close(false, objOpt, objOpt);
                        excel.Quit();
                        excel = null;
                        if (this.IsHandleCreated)
                        {
                            this.Invoke(new MethodInvoker(delegate()
                            {
                                label1.Text         = "导出成功!";
                                label1.Left         = (this.Width - label1.Width) / 2;
                                btn_Export.Text     = "确定";
                                btn_Export.Click   -= new EventHandler(btn_Export_Click);
                                btn_Export.Click   += new EventHandler(btn_Export_Exit);
                                pictureBox2.Visible = false;
                                lblExport.Visible   = false;
                            }));
                        }

                        //MessageBox.Show("导出成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch
                    {
                        wkb.Close(false, objOpt, objOpt);
                        excel.Quit();
                        if (this.IsHandleCreated)
                        {
                            this.Invoke(new MethodInvoker(delegate()
                            {
                                this.Close();
                            }));
                        }
                    }
                }
                else
                {
                    wkb.Close(false, objOpt, objOpt);
                    excel.Quit();
                    if (this.IsHandleCreated)
                    {
                        this.Invoke(new MethodInvoker(delegate()
                        {
                            this.Close();
                        }));
                    }
                }
                #endregion
            }
            catch (Exception ee)
            {
                if (!ee.Message.ToString().Equals("正在中止线程。"))
                {
                    MessageBox.Show("Excel导出失败[" + ee.Message + "][" + ee.StackTrace + "]");
                }
            }
        }
示例#12
0
        public static void GetDataTable(PrintModel model, DataGridView dgv)
        {
            List<string> strColumns = new List<string>();
            List<string> strHeaderText = new List<string>();
            DataTable DtTemp = null;
            try
            {
               
                DtTemp = (dgv.DataSource as DataTable).Copy();
                //删除隐藏的datatcolumn列
                foreach (DataGridViewColumn col in dgv.Columns)
                {
                    if (col.Visible == false)//|| col.GetType().ToString() == "System.Windows.Forms.DataGridViewCheckBoxColumn"
                    {
                        if (DtTemp.Columns.Contains(col.Name))
                            DtTemp.Columns.Remove(col.Name);
                    }
                }

                for (int i = 0; i < dgv.Columns.Count; i++)
                {
                    strColumns.Add("");
                    strHeaderText.Add("");
                }

                for (int i = 0; i < dgv.Columns.Count; i++)
                {
                    if (dgv.Columns[i].Visible == true)
                    {
                        strColumns[dgv.Columns[i].DisplayIndex] = dgv.Columns[i].Name.ToString();
                        strHeaderText[dgv.Columns[i].DisplayIndex] = dgv.Columns[i].HeaderText.ToString();
                    }
                }
                while (strColumns.Contains(""))
                {
                    strColumns.Remove("");
                    strHeaderText.Remove("");
                }
                
                //根据保存的模板设置列顺序
                if (model.Columns.Count != 0 && DtTemp.TableName != "Table" && DtTemp.TableName != "A_InitialData")
                {
                    //设置datatable列索引
                    //string[] tempStr = model.Columns.Split(',');
                    for (int i = 0; i < model.Columns.Count; i++)
                    {
                        DtTemp.Columns[model.Columns[i].ToString()].SetOrdinal(i);
                    }
                }
                else
                {
                    //根据displayindex设置列顺序
                    for (int i = 0; i < strColumns.Count; i++)
                    {
                        DtTemp.Columns[strColumns[i]].SetOrdinal(i);
                    }
                }
                if (strColumns.Count != 0 && strColumns.Count != 0)
                {
                    model.Columnname = strColumns;
                    model.Columntext = strHeaderText;
                }
            }
            catch(Exception ee)
            {
                if (DtTemp == null)
                {
                    if (!ee.Message.Equals("正在中止线程。"))
                    {
                        MessageBox.Show("由于系统错误导出任务未执行", "提示");
                    }
                    return;
                }
            }
            model.Printtable = DtTemp;
        }
示例#13
0
        /// <summary>
        /// 获取Model
        /// </summary>
        /// <param name="Grid"></param>
        /// <param name="PrintName"></param>
        /// <param name="TjTime"></param>
        /// <returns></returns>
        public static PrintModel getMode(DataGridView Grid, string PrintName, string TjTime)
        {
            PrintModel model = new PrintModel();

            #region[加载打印基础配置信息]
            //if (TjTime.ToString().Contains("统计时间"))
            //{
            //    model.Tjtime = Grid.;
            //}
            //else
            //{
            //    model.Tjtime = "";
            //}
            model.Tjtime = "共 "+Grid.Rows.Count+" 条记录";
            string tableName = string.Empty;
         
            tableName = (Grid.DataSource as DataTable).TableName.ToString();
            if (!Directory.Exists(Application.StartupPath.ToString() + "\\PrintSetModel"))
            {
                Directory.CreateDirectory(Application.StartupPath.ToString() + "\\PrintSetModel");
            }
            if (!File.Exists(Application.StartupPath.ToString() + "\\PrintSetModel\\" + tableName + ".xml"))
            {
                FileStream fs = new FileStream(Application.StartupPath.ToString() + "\\PrintSetModel\\" + tableName + ".xml", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamWriter ws = new StreamWriter(fs);
                ws.WriteLine("<PrintSet>");
                ws.WriteLine("<TableName></TableName>");
                ws.WriteLine("<Font>");
                ws.WriteLine("<TitleFont>宋体,21.75,Center</TitleFont>");
                ws.WriteLine("<subTitleFont>宋体,7.5,Center</subTitleFont>");
                ws.WriteLine("<ContentFont>宋体,7.5,Center</ContentFont>");
                ws.WriteLine("<SignFont>宋体,10.5,Center</SignFont>");
                ws.WriteLine("</Font>");
                ws.WriteLine("<PageSet>");
                ws.WriteLine("<PageSize>21,29.7</PageSize>");//cm
                ws.WriteLine("<Margin>0.5,0.5,0.5,0.5</Margin>");//cm
                ws.WriteLine("</PageSet>");
                ws.WriteLine("<Sign>");
                ws.WriteLine("<LeaderList>制表人,,,</LeaderList>");
                ws.WriteLine("</Sign>");
                ws.WriteLine("<Content>");
                ws.WriteLine("<Columns></Columns>");
                ws.WriteLine("<Width></Width>");
                ws.WriteLine("</Content>");
                ws.WriteLine("</PrintSet>");
                ws.Close();
                ws.Dispose();
                fs.Close();
                fs.Dispose();
            }
            XmlDocument doc = new XmlDocument();
            doc.Load(Application.StartupPath.ToString() + "\\PrintSetModel\\" + tableName + ".xml");
            //表格名称
            
            model.Printname = doc.SelectSingleNode("/PrintSet/TableName").InnerText.ToString();
            if (model.Printname == "")
                model.Printname = PrintName;
            //标题栏字体
            string[] Temp = doc.SelectSingleNode("/PrintSet/Font/TitleFont").InnerText.ToString().Trim().Split(',');
            model.Titlefontfamily = Temp[0].ToString();
            model.Titlefontsize = (float)(Convert.ToDouble(Temp[1].ToString()));
            model.Titlefontstyle = Temp[2].ToString();

            //副标题字体
            Temp = doc.SelectSingleNode("/PrintSet/Font/subTitleFont").InnerText.ToString().Trim().Split(',');
            model.Subfontfamily = Temp[0].ToString();
            model.Subfontsize = (float)(Convert.ToDouble(Temp[1].ToString()));
            model.Subfontstyle = Temp[2].ToString();

            //表格字体
            Temp = doc.SelectSingleNode("/PrintSet/Font/ContentFont").InnerText.ToString().Trim().Split(',');
            model.Contentfontfamily = Temp[0].ToString();
            model.Contentfontsize = (float)(Convert.ToDouble(Temp[1].ToString()));
            model.Contentfontstyle = Temp[2].ToString();

            //签名栏字体
            Temp = doc.SelectSingleNode("/PrintSet/Font/SignFont").InnerText.ToString().Trim().Split(',');
            model.Signfontfamily = Temp[0].ToString();
            model.Signfontsize = (float)(Convert.ToDouble(Temp[1].ToString()));
            model.Signfontstyle = Temp[2].ToString();

            //纸张大小
            Temp = doc.SelectSingleNode("/PrintSet/PageSet/PageSize").InnerText.ToString().Trim().Split(',');
            model.Paperwidth = Temp[0].ToString();
            model.Paperheight = Temp[1].ToString();

            //纸张边距
            Temp = doc.SelectSingleNode("/PrintSet/PageSet/Margin").InnerText.ToString().Trim().Split(',');
            model.Papertop = Temp[0].ToString();
            model.Paperbottom = Temp[1].ToString();
            model.Paperleft = Temp[2].ToString();
            model.Paperright = Temp[3].ToString();

            //签名栏内容
            model.Signcontent = doc.SelectSingleNode("/PrintSet/Sign/LeaderList").InnerText.ToString().Trim();

            //表格选择的列名集合
            string temp = doc.SelectSingleNode("/PrintSet/Content/Columns").InnerText.ToString().Trim();
            if (temp != "")
            {
                foreach (string strTemp in temp.Split(','))
                {
                    model.Columns.Add(strTemp);
                }
            }

            //表格选择的列宽集合
            temp = doc.SelectSingleNode("/PrintSet/Content/Width").InnerText.ToString().Trim();
            if (temp != "")
            {
                foreach (string strTemp in temp.Split(','))
                {
                    model.Columnswidth.Add(strTemp);
                }
            }
            #endregion

            //加工成有效的数据源
            GetDataTable(model, Grid);

            return model;
        }