欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

WPF 导出Excel 导出图片

程序员文章站 2022-07-13 23:07:21
...
        /// <summary>
        /// 导出Excel
        /// </summary>
        private void ExportExcel(DataTable ExcelDt)
        {
            //导出表格
            HSSFWorkbook workBook = new HSSFWorkbook();
            ISheet sheet1 = workBook.CreateSheet("表名");
            //表头
            IRow headerRow = sheet1.CreateRow(0);
            foreach (DataColumn column in ExcelDt.Columns)
            {
                headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
            }
            int rowIndex = 1;
            foreach (DataRow dr in ExcelDt.Rows)
            {
                IRow dataRow = sheet1.CreateRow(rowIndex++);
                foreach (DataColumn column in ExcelDt.Columns)
                {
                    dataRow.CreateCell(column.Ordinal).SetCellValue(dr[column.ColumnName].ToString());
                }
            }
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.DefaultExt = ".xls";
            sfd.Filter = "(*.xls)|*.xls";
            if (sfd.ShowDialog() == true)
            {
                try
                {
                    FileStream file = new FileStream(sfd.FileName, FileMode.Create);
                    workBook.Write(file);
                    file.Dispose();
                    MessageDialog.Show("导出成功!", "提示");
                }
                catch (Exception)
                {
                    MessageDialog.Show("该文件正在被其他进程占用,导出失败!", "提示");
                }
            }
        }

  使用NPOI.dll ,上述代码是使用DLL 1.2.4.0,可能使用的DLL不同,代码略有不同。比如,有的版本的NPOI.dll 的是使用的是Sheet而非ISheet。

 

2.导出图片

        /// <summary>
        /// 图片转化为bitmap
        /// </summary>
        /// <param name="chartTemp"></param>
        /// <returns></returns>
        private Bitmap GetControlMap(Control ctrl)
        {
            System.Windows.Point point = ctrl.PointToScreen(new System.Windows.Point(0, 0));
            System.Drawing.Bitmap bitmap = new Bitmap((int)ctrl.Width, (int)ctrl.Height);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            System.Drawing.Size size = new System.Drawing.Size((int)ctrl.Width, (int)ctrl.Height);
            g.CopyFromScreen((int)point.X, (int)point.Y, 0, 0, size);
            return bitmap;
        }

  

        /// <summary>
        /// 导出图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnToImage_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.DefaultExt = ".jpg";
            sfd.Filter = "(*.jpg)|*.jpg";
            if (sfd.ShowDialog() == true)
            {
                Bitmap bitmap = GetControlMap(humiCloud);
                bitmap.Save(sfd.FileName);
                MessageDialog.Show("导出成功!", "提示");
            }
        }