[WPF]读取excel

  /// <summary>
        /// 将excel文档转换成PDF格式
        /// </summary>
        /// <param name="sourcePath">原文件路径</param>
        /// <param name="targetPath">文件转换为PDF保存的路径</param>
        /// <param name="targetType">枚举类型参数</param>
        /// <returns></returns>
        private bool ExcelConvert(string sourcePath, string targetPath, XlFixedFormatType targetType)
        {
            bool result;
            object missing = Type.Missing;
            Microsoft.Office.Interop.Excel.Application application = null;
            Workbook workBook = null;
            try
            {
                if (!File.Exists(targetPath))
                {
                    application = new Microsoft.Office.Interop.Excel.Application();
                    object target = targetPath;
                    object type = targetType;
                    workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing,
                            missing, missing, missing, missing, missing, missing, missing, missing, missing);

                    workBook.ExportAsFixedFormat(targetType, target, XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);
                    result = true;
                }
                else
                {
                    result = true;
                }
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (workBook != null)
                {
                    workBook.Close(true, missing, missing);
                    workBook = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }


//页面调用
 bool result = ExcelConvert(path + filename, path + filename + ".xps", XlFixedFormatType.xlTypeXPS);
                        if (result)
                        {
                            DocumentViewer docViewer = new DocumentViewer();
                            docViewer.Document = new XpsDocument((path + filename + ".xps"), System.IO.FileAccess.Read).GetFixedDocumentSequence();

                            docViewer.FitToWidth();
                            grid1.Children.Add(docViewer);
                            docViewer.SetValue(Grid.RowProperty, 0);
                            docViewer.SetValue(Grid.ColumnProperty, 0);
                        }
                        else
                        {
                            Xceed.Wpf.Toolkit.MessageBox.Show("系统调用有误,是否安装Office软件");
                        }

 

posted on 2019-05-30 09:15  菜鸟也想上天  阅读(1685)  评论(1编辑  收藏  举报