输出datagridview到pdf

这段代码演示了如何从DataGridView控件中导出数据到PDF文件。首先,它遍历DataGridView的每一行,将数据存储在二维字符串数组中。接着,它创建一个Excel文件作为模板,并将数据填充到模板中。最后,将Excel文件转换为PDF并保存。整个过程中涉及了日期格式化、字符串操作以及使用Excel Interop库进行文件操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 private void outputDatagridview(DataGridView dataGridView1)
        {




            //获取行数
            int count = dataGridView1.Rows.Count - 1;
            //分配数组,列数为输出表格的列数,共11列
            string[,] str = new string[count, 11];
            //利用一个For循环,完成对每一次餐费的填充,每一次循环为一行的填充,存在数组里
            for (int i = 0; i <= count - 1; i++)
            {
                //0外业时间String.Format(    "yyyy-MM-dd    ",yourDateTime);
                DateTime time = (DateTime)dataGridView1["WYSJ", i].Value;
                str[i, 0] = time.ToString("yyyy-MM-dd");


                //1项目名称
                str[i, 1] = dataGridView1["GCMC", i].Value.ToString();
                //3餐费
                str[i, 3] = dataGridView1["YCFY", i].Value.ToString();
                //6用餐人数
                string CTGCG = dataGridView1["CTGCG", i].Value.ToString();
                string CTFZG = dataGridView1["CTFZG", i].Value.ToString();
                string DTGCG = dataGridView1["DTGCG", i].Value.ToString();
                string DTFZG = dataGridView1["DTFZG", i].Value.ToString();
                string GXFZG = dataGridView1["GXFZG", i].Value.ToString();
                string GXTCCG = dataGridView1["GXTCCG", i].Value.ToString();
                string QTGCFUG = dataGridView1["QTGCFZG", i].Value.ToString();
                string QTGCGCG = dataGridView1["QTGCGCG", i].Value.ToString();
                string sj = dataGridView1["SJ", i].Value.ToString();


                string all = CTGCG + CTFZG + DTGCG + DTFZG + GXFZG + GXTCCG + QTGCFUG + QTGCGCG;
                int no;
                if (sj == "" || sj == null || sj == "无")
                {
                    string[] num = all.Split(',');
                    no = num.Length - 1;
                    str[i, 6] = no.ToString();
                }
                else
                {


                    if (all.Contains(sj))
                    {


                        string[] num = all.Split(',');
                        no = num.Length - 1;
                        str[i, 6] = no.ToString();
                    }
                    else
                    {
                        string[] num = all.Split(',');
                        no = num.Length;
                        str[i, 6] = no.ToString();
                    }


                }
                //7餐票张数
                str[i, 7] = "";
                //8人均餐费
                double money = Convert.ToDouble(str[i, 3]) / no;
                str[i, 8] = money.ToString();
                //9经手人
                str[i, 9] = dataGridView1["JFR", i].Value.ToString();
                //10备注,这里的备注指的是“住宿费:元,其他:元”,写个方法用来区分住宿费和其他费用,存在数组里。
                //同时,需要根据备注中的内容读出住宿费,其他费用字段。
                //MessageBox.Show("住宿费:元,其他:元".Length.ToString ());
                str[i, 10] = dataGridView1["BZ", i].Value.ToString();
                if (str[i, 10].Length == 10 || str[i, 10] == "")
                {
                    str[i, 4] = "0";
                    str[i, 5] = "0";
                    str[i, 2] = str[i, 3];
                }
                else
                {
                    //分割备注信息


                    string[] BZsplit = str[i, 10].Split(',');
                    string Zhusu = BZsplit[0];
                    string Qita = BZsplit[1];


                    string[] Arrayzhusu = Zhusu.Split(':');
                    int index1 = Arrayzhusu[1].LastIndexOf("元");
                    string zhusufei = Arrayzhusu[1].Substring(0, index1).Trim();




                    string[] ArrayQita = Qita.Split(':');
                    int index2 = ArrayQita[1].LastIndexOf("元");
                    string Qitafei = ArrayQita[1].Substring(0, index2).Trim();




                    //str[i, 4] = zhusufei;
                    //str[i, 5] = Qitafei;


                    double zhusufeiyong;
                    double qitafeiyong;
                    double canfei;


                    if (zhusufei == "" || zhusufei == " ")
                    {
                        zhusufeiyong = 0;
                        str[i, 4] = "0";
                    }
                    else
                    {
                        zhusufeiyong = Convert.ToDouble(zhusufei);
                        str[i, 4] = zhusufei;
                    }
                    if (Qitafei == "" || Qitafei == " ")
                    {
                        qitafeiyong = 0;
                        str[i, 5] = "0";


                    }
                    else
                    {
                        qitafeiyong = Convert.ToDouble(Qitafei);
                        str[i, 5] = Qitafei;
                    }






                    canfei = Convert.ToDouble(str[i, 3]);


                    double zonghe = zhusufeiyong + qitafeiyong + canfei;


                    str[i, 2] = zonghe.ToString();


                }


            }






            //输出成Excel文件
            string filename = "";
            string filepath = "";
            string excelfilename = "";
            SaveFileDialog mySave = new SaveFileDialog();
            // mySave.Filter = "Excel文件(*.XLS)|*.xls|所有文件(*.*)|(*.*)";
            mySave.Filter = "pdf文件(*.pdf)|*.pdf|所有文件(*.*)|(*.*)";
            if (mySave.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            else
            {


                filename = mySave.FileName;
                filepath = Path.GetDirectoryName(filename);
                excelfilename = filepath + "\\temp.xls";
                string filenameold = mySave.FileName;
                //自动建立与共享资源的连接
                Process p = new Process();
                p.StartInfo.FileName = "cmd.exe";
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                p.StartInfo.CreateNoWindow = true;
                p.Start();
                //执行dos命令
                //断开连接
                p.StandardInput.WriteLine(@"net use \\192.168.106.33\IPC$ /delete");
                //建立连接
                p.StandardInput.WriteLine(@"net use \\192.168.106.33\IPC$ ");
                p.Close();
                p.Dispose();
                FileInfo mode = new FileInfo(@"\\192.168.106.33\报表模板\测量生产运营管理系统\报销明细.xls");
                try
                {
                    mode.CopyTo(excelfilename, true);
                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message);
                    return;
                }
                //打开复制后的文件 
                object missing = Missing.Value;
                Microsoft.Office.Interop.Excel.Application myExcel = new Microsoft.Office.Interop.Excel.Application();
                // 打开模板文件,得到WorkBook对象 
                Microsoft.Office.Interop.Excel.Workbook workBook = myExcel.Workbooks.Open(excelfilename, missing, missing, missing, missing, missing,
                                      missing, missing, missing, missing, missing, missing, missing, missing, missing);


                // 得到WorkSheet对象 
                //工程月度表
                Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets.get_Item(1);
                //重命名
                //将Excel显示出来
                myExcel.Visible = false;
                this.Close();
                double Sumfeiyong = 0;
                double Sumcanfei = 0;
                double Sumzhusufei = 0;
                double Sumqitafei = 0;
                for (int x = 0; x < str.GetLength(0); x++)
                {
                    workSheet.Cells[3 + x, 1] = str[x, 0];
                    workSheet.Cells[3 + x, 2] = str[x, 1];
                    workSheet.Cells[3 + x, 3] = str[x, 2];
                    workSheet.Cells[3 + x, 4] = str[x, 3];
                    workSheet.Cells[3 + x, 5] = str[x, 4];
                    workSheet.Cells[3 + x, 6] = str[x, 5];
                    workSheet.Cells[3 + x, 7] = str[x, 6];
                    workSheet.Cells[3 + x, 8] = str[x, 7];
                    workSheet.Cells[3 + x, 9] = str[x, 8];
                    workSheet.Cells[3 + x, 10] = str[x, 9];
                    if (str[x, 10] == "住宿费:元,其他:元" || str[x, 10] == "")
                    {
                        workSheet.Cells[3 + x, 11] = "";


                    }
                    else
                    {
                        workSheet.Cells[3 + x, 11] = str[x, 10];
                    }


                    Sumfeiyong += Convert.ToDouble(str[x, 2]);
                    Sumcanfei += Convert.ToDouble(str[x, 3]);
                    Sumzhusufei += Convert.ToDouble(str[x, 4]);
                    Sumqitafei += Convert.ToDouble(str[x, 5]);


                }
                //表格最后一行,输出各类金额的合计
                workSheet.Cells[3 + str.GetLength(0), 2] = "合计";
                workSheet.Cells[3 + str.GetLength(0), 3] = Sumfeiyong.ToString();
                workSheet.Cells[3 + str.GetLength(0), 4] = Sumcanfei.ToString();
                workSheet.Cells[3 + str.GetLength(0), 5] = Sumzhusufei.ToString();
                workSheet.Cells[3 + str.GetLength(0), 6] = Sumqitafei.ToString();
                //添加对单元格边框
                int Rowcount = workSheet.UsedRange.CurrentRegion.Rows.Count;
                Range range = workSheet.get_Range(workSheet.Cells[1, 1], workSheet.Cells[Rowcount, 11]);
                range.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                //MessageBox.Show(Rowcount.ToString());
                //保存修改 
                workBook.Save();
                workBook.Close();


                MessageBox.Show("输出成功!");


                System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel);


                workBook = null;
                workSheet = null;
                range = null;
                myExcel = null;


                GC.Collect();


                XlFixedFormatType parameter = XlFixedFormatType.xlTypePDF;
                //以实现生成pdf,下一步需要删除excel,并且不显示Excel,并且excel指定位置存储,用完就删,或者在
                //f服务器备份,选择存放位置改为pdf的存放位置
                Convert2PDF(excelfilename, filename, parameter);


                if (File.Exists(excelfilename))
                {
                    File.Delete(excelfilename);
                }


            }
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值