获取TextBox1中存储的文件进行转换

问题描述 投票:0回答:2

美好的一天。

我是编码新手,需要你的帮助。

我正在尝试创建一个可以实现的应用程序。

  1. 通过浏览按钮浏览所有doc、XLS和ppt文件,并将在TextBox1中显示文件名。
  2. 当我单击“转换”按钮时,它将从 TextBox1 抓取文件,并将 doc 转换为 docs、XLS 转换为 XLSX、ppt 转换为 PPTX。

我成功浏览文件并显示 TextBox1 中的所有文件,但无法从 TextBox1 获取/选择文件进行转换。

我在寻找什么?

  1. 在Convert Button代码中获取TextBox1中存储的文件。
  2. 将这些文件转换为相关的新格式。
  3. 在加载栏/进度栏中显示数据,以便我可以了解转换需要多长时间。

到目前为止我在不同论坛上尝试过的内容分享如下

using System;
using System.Collections.Generic;
//using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Spire.Doc;
using Spire.Xls;
using Spire.Presentation;
using Microsoft.Office.Interop.Excel;

namespace T_Converter
{
    public partial class Form1 : Form
    {
        private object workbook;

        public object ExcelVersion { get; private set; }

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            BTNClear.Enabled = false;
            BTNConvert.Enabled = false;
        }

        private void BTNBrowse_Click(object sender, EventArgs e)
        {
            var dialog = new OpenFileDialog();
            dialog.InitialDirectory = @"\Desktop";
            dialog.Title = "Browse old office files";
           // dialog.Filter = "Office Files (*.xls)|*.xls";
            dialog.DefaultExt = ".xls";

            
            //OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;
           

            var result = dialog.ShowDialog();

            foreach (string file in dialog.FileNames)
            {
                textBox1.AppendText(Path.GetFileName(file) + Environment.NewLine);
            }

            
            BTNConvert.Enabled = true;
                BTNClear.Enabled = true;

        }

        private void BTNClear_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
            BTNClear.Enabled = false;
            BTNConvert.Enabled = false;
        }

        private void BTNClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void BTNConvert_Click(object sender, EventArgs e)
        {
            
        }
    }

            //Create a Workbook instance
            
            namespace ConvertXlsToXlsx

    {

        class Program

        {

            static void main(string[] args)

            {

                //Create a Workbook instance

                Excel.Workbook workbook = new Excel.Workbook();

                //Load an XLS file

                Workbook.LoadFromFile(@"\Desktop\Test.xlsx");



                //Convert the file to XLSX format

                workbook.SaveToFile(@"C:\Users\Test\Desktop\test.xlsx", ExcelVersion.Version2016);
                MessageBox.Show("OK");
            }

        }

    }

}
    
c# xlsx xls spire.xls
2个回答
0
投票

以下代码解决了我的问题。这篇文章的回复也有帮助,但我们公司的专家找到了完整的解决方案。

private void BTNBrowse_Click(object sender, EventArgs e)
    {
        var dialog = new OpenFileDialog();
        dialog.InitialDirectory = @"\Desktop";
        dialog.Title = "Browse old office files";
        dialog.Filter = "Excel Files (*.xls)|*.xls|Word Files(*.doc)|*.doc|PowerPoint Files(*.ppt)|*.ppt";
        dialog.DefaultExt = ".xls";

        dialog.Multiselect = true;

        var result = dialog.ShowDialog();

        foreach (string file in dialog.FileNames)
        {

            textBox1.AppendText(file + Environment.NewLine);
        }
        // Update textbox2 with the total number of selected files in a formatted way
        int totalFiles = dialog.FileNames.Length;
        textBox2.Text = $"{totalFiles:D3}";

        BTNConvert.Enabled = true;
        BTNClear.Enabled = true;

    }

    private void BTNClear_Click(object sender, EventArgs e)
    {
        textBox1.Clear();
        BTNClear.Enabled = false;
        BTNConvert.Enabled = false;
        progressBar1.Value = 0;
        textBox2.Text = "000";
    }

    private void BTNClose_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    private void BTNConvert_Click(object sender, EventArgs e)
    {
        // ProgressBar
        backgroundWorker1.WorkerReportsProgress = true;
        backgroundWorker1.RunWorkerAsync();

        string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        string outputFolder = Path.Combine(desktopPath, "Converted Files");

        // Loop for multiple files
        for (int i = 0; i < textBox1.Lines.Length; i++)
        {
            string filepath = textBox1.Lines[i].Replace("\r\n", string.Empty);

            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filepath);
            string outputFilePath = Path.Combine(outputFolder, fileNameWithoutExtension);

            if (filepath.EndsWith(".xls"))
            {
                Excel.Application excelApp = null;
                Excel.Workbook workbook = null;

                try
                {
                    excelApp = new Excel.Application();
                    workbook = excelApp.Workbooks.Open(filepath);

                    string outputXlsxFilePath = outputFilePath + ".xlsx";

                    workbook.SaveAs(outputXlsxFilePath, Excel.XlFileFormat.xlOpenXMLWorkbook);
                }
                catch (Exception ex)
                {
                    // Handle exceptions
                }
                finally
                {
                    if (workbook != null)
                        Marshal.ReleaseComObject(workbook);

                    if (excelApp != null)
                    {
                        excelApp.Quit();
                        Marshal.ReleaseComObject(excelApp);
                    }
                }
            }
            else if (filepath.EndsWith(".doc"))
            {
                Application wordApp = null;
                Document doc = null;

                try
                {
                    wordApp = new Application();
                    doc = wordApp.Documents.Open(filepath);

                    string outputDocxFilePath = outputFilePath + ".docx";

                    doc.SaveAs2(outputDocxFilePath, WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: WdCompatibilityMode.wdWord2013);
                }
                catch (Exception ex)
                {
                    // Handle exceptions
                }
                finally
                {
                    if (doc != null)
                        doc.Close();

                    if (wordApp != null)
                    {
                        wordApp.Quit();
                        Marshal.ReleaseComObject(wordApp);
                    }
                }
            }
            else if (filepath.EndsWith(".ppt"))
            {
                PowerPoint.Application pptApp = null;
                PowerPoint.Presentation presentation = null;

                try
                {
                    pptApp = new PowerPoint.Application();
                    presentation = pptApp.Presentations.Open(filepath,
                        Microsoft.Office.Core.MsoTriState.msoTrue,
                        Microsoft.Office.Core.MsoTriState.msoFalse,
                        Microsoft.Office.Core.MsoTriState.msoFalse);

                    string outputPptxFilePath = outputFilePath + ".pptx";

                    presentation.SaveAs(outputPptxFilePath, PowerPoint.PpSaveAsFileType.ppSaveAsOpenXMLPresentation, Microsoft.Office.Core.MsoTriState.msoTriStateMixed);
                }
                catch (Exception ex)
                {
                    // Handle exceptions
                }
                finally
                {
                    if (presentation != null)
                        presentation.Close();

                    if (pptApp != null)
                    {
                        pptApp.Quit();
                        Marshal.ReleaseComObject(pptApp);
                    }
                }
            }
        }

        MessageBox.Show("Conversion completed. \nYour converted files are saved in ''Converted Files'' folder created on your desktop.");
    }


    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        for (int j = 1; j <= 100; j++)
        {
            // Wait 50 milliseconds.  
            Thread.Sleep(50);
            // Report progress.  
            backgroundWorker1.ReportProgress(j);

        }

    }

    private void backgroundWorker1_ProgressChange(object sender, ProgressChangedEventArgs e)
    {
        // Change the value of the ProgressBar   
        progressBar1.Value = e.ProgressPercentage;
        // Set the text.  
        this.Text = e.ProgressPercentage.ToString();
    }
}

}


-1
投票

问题已解决。 谢谢大家的帮助和支持。

© www.soinside.com 2019 - 2024. All rights reserved.