合并excel文档

时间:2017-09-17 20:23:55

标签: c# wpf excel

我正在尝试创建一个简单的程序来合并excel文件,并且无法单独加载ListBox中的文件。

用户可以选择出现在ListBox中的多个文件,然后在单击合并时,会生成一个新文件,其名称在侧面的TextBox中给出。

我的问题是当我来加载要从ListBox合并的文件时。

btnMergeFile_Click(object sender, RoutedEventArgs e)
    {
        Workbook workbook = new Workbook();
        workbook.LoadFromFile(@"filename.xlsx");
        Workbook workbook2 = new Workbook();
        workbook2.LoadFromFile(@"filename.xlsx");
    }

是否可以单独调用列表名称?

抱歉,我是c#和wpf的新手。

XAML

    <DockPanel Margin="10">
        <WrapPanel HorizontalAlignment="Center" DockPanel.Dock="Top" Margin="0,0,0,10">
            <Button x:Name="btnSelectFile" Width="75" Height="30" Margin="5" Click="btnSelectFile_Click">Select Files</Button>
            <Button x:Name="btnMergeFile" Width="75" Height="30" Margin="5" Click="btnMergeFile_Click">Merge Files</Button>
            <Button x:Name="btnClearFile" Width="75" Height="30" Margin="5" Click="btnClearFile_Click">Clear Files</Button>
            <TextBox x:Name="newFileName" TextAlignment="Left" HorizontalAlignment="Center" Width="150" Text="New File Name"/>
        </WrapPanel>
        <ListBox x:Name="listBox1" />
    </DockPanel>

</Grid>

.CS

using System;
using System.Windows;
using Microsoft.Win32;
using System.Data;
using Spire.Xls;

namespace ExcelMerge_1._1
{

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    public void btnSelectFile_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Multiselect = true;
        openFileDialog.Filter = "csv files (*.csv)|*.csv|Excel files (*.XLSX)|*.XLSX";
        openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

        if (openFileDialog.ShowDialog() == true)
        {
            foreach (string filename in openFileDialog.FileNames)

                listBox1.Items.Add(System.IO.Path.GetFullPath(filename));
        }

    }



    public void btnMergeFile_Click(object sender, RoutedEventArgs e)
    {
        Workbook workbook = new Workbook();
        workbook.LoadFromFile(@"filename.xlsx");
        Workbook workbook2 = new Workbook();
        workbook2.LoadFromFile(@"filename.xlsx");


        Worksheet sheet2 = workbook2.Worksheets[0];
        DataTable dataTable = sheet2.ExportDataTable();
        Worksheet sheet1 = workbook.Worksheets[0];
        sheet1.InsertDataTable(dataTable, false, sheet1.LastRow + 1, 1);

        workbook.SaveAsXml(newFileName.Text);
    }

    private void btnClearFile_Click(object sender, RoutedEventArgs e)
    {
        listBox1.Items.Clear();
    }
}
}

3 个答案:

答案 0 :(得分:0)

我猜您只需要获取之前在列表框中添加的项目,这样您就可以使用添加项目时使用的相同集合:

foreach(var fileName in listBox1.Items)
{
     Workbook workbook = new Workbook();
     workbook.LoadFromFile(fileName);
}

但作为初学者,我建议您阅读有关MVVM架构的内容,它不仅可以帮助您完成此方案,还可以保持代码的逻辑结构。你可以看到另一个问题: MVVM: Tutorial from start to finish?

答案 1 :(得分:0)

您提到用户可以选择多个文件,因此我认为您需要这样:

<ListBox x:Name="listBox1" SelectionMode="Multiple" />

此外,您还可以使用ListBox.SelectedItems集合来迭代这些选定的文件 此外,您还可以尝试完整的btnMergeFile_Click活动:

private void btnMergeFile_Click(object sender, RoutedEventArgs e)
{
    ExcelFile workbook = new ExcelFile();

    // Copy all sheets into a resulting ExcelFile.
    foreach (string file in this.listBox1.SelectedItems)
    {
        ExcelFile temp = ExcelFile.Load(file);
        foreach (ExcelWorksheet sheet in temp.Worksheets)
            workbook.Worksheets.AddCopy(
                // Unique sheet name.
                string.Format("{0} - {1}", System.IO.Path.GetFileNameWithoutExtension(file), sheet.Name),
                // Sheet object.
                sheet);
    }

    // Save ExcelFile.
    workbook.Save(this.newFileName.Text);
}

注意,我已使用GemBox.Spreadsheet合并所选的Excel文件。

答案 2 :(得分:0)

首先,您需要将列表框的选择模式设置为多个,如NixonUposseen建议的那样。

其次,使用如下代码合并选定的excel文件和csv文件。我已经尝试过了,它在我身边运作良好。

using System;
using System.Windows;
using Microsoft.Win32;
using Spire.Xls;
using System.IO;

namespace MergeExcel
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }        

        private void btnSelectFile_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Multiselect = true;
            openFileDialog1.Title = "Select Files";
            openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            openFileDialog1.Filter = "Files(*.xls;*.xlsx;*.csv)|*.xls;*.xlsx;*.csv";            
            openFileDialog1.FilterIndex = 1;
            openFileDialog1.RestoreDirectory = true;
            //openFileDialog1.CheckFileExists = true;
            //openFileDialog1.CheckPathExists = true;

            if (openFileDialog1.ShowDialog() == true)
            {
                foreach (string filename in openFileDialog1.FileNames)
                {

                    listBox1.Items.Add(System.IO.Path.GetFullPath(filename));
                }
            }
        }

        private void btnMergeFile_Click(object sender, RoutedEventArgs e)
        {
            Workbook tempbook = new Workbook();

            Workbook workbook = new Workbook();
            workbook.Version = ExcelVersion.Version2013;
            workbook.Worksheets.Clear();


            foreach (string file in listBox1.SelectedItems)
            {
                string extension = Path.GetExtension(file);
                if (extension == ".xlsx" | extension == ".xls")
                {
                    tempbook.LoadFromFile(file);//Load Excel files
                }
                else
                {
                    tempbook.LoadFromFile(file, ",", 1, 1);//Load CSV files                      
                }
                foreach (Worksheet sheet in tempbook.Worksheets)
                {
                    workbook.Worksheets.AddCopy(sheet);//Merge files
                }
            }
            string newFileName = textBox1.Text.Trim();
            workbook.SaveToFile(newFileName);
        }       

    }
}