C#Excel to txt转换并格式化输出WPF

时间:2015-05-25 09:30:48

标签: c# wpf excel

我目前有一个带有2个按钮的WPF应用程序,一个用于选择文件,另一个用于将所选文件转换为.txt格式。现在我需要让另一个按钮读取excel文件并格式化数据并生成.txt文件。

我的代码如下所示:

if

我将使用此文件的Excel文件将如下所示:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

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

    private void BtnFileOpen_Click(object sender, RoutedEventArgs e)
    {
        var fileDialog = new System.Windows.Forms.OpenFileDialog();
        var result = fileDialog.ShowDialog();
        switch (result)
        {
            case System.Windows.Forms.DialogResult.OK:
                var excelFilePath = fileDialog.FileName;
                TxtFile.Text = excelFilePath;
                TxtFile.ToolTip = excelFilePath;
                break;
            case System.Windows.Forms.DialogResult.Cancel:
            default:
                TxtFile.Text = null;
                TxtFile.ToolTip = null;
                break;
        }

    }

    private void convert_Click(object sender, RoutedEventArgs e)
    {
         exportExcelToTxt;
    }
    static void exportExcelToTxt(string excelFilePath, string outputTxtPath)
    {
        Dictionary<string, List<long>> values = new Dictionary<string, List<long>>();
        using (OleDbConnection excelConnection = new OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0;HDR=YES", excelFilePath)))
        {
            excelConnection.Open();
            string firstSheet = getFirstSheetName(excelConnection);
            using (OleDbCommand cmd = excelConnection.CreateCommand())
            {
                cmd.CommandText = string.Format("SELECT * FROM [{0}]", firstSheet);
                using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
                {
                    using (DataTable dt = new DataTable())
                    {
                        da.Fill(dt); // Getting all the data in the sheet
                        foreach (DataRow item in dt.Rows)
                        {
                            List<long> toAdd = new List<long>();
                            string key = item[0] as string;
                            for (int i = 1; i < dt.Columns.Count; i++)
                            {
                                toAdd.Add(Convert.ToInt64(item[i]));
                            }
                            values.Add(key, toAdd); // Associating all the "numbers" to the "Name"
                        }
                    }
                }
            }
        }
        StringBuilder toWriteToTxt = new StringBuilder();
        foreach (KeyValuePair<string, List<long>> item in values)
        {
            // Formatting the output
            toWriteToTxt.Append(string.Format("{0}:", item.Key));
            foreach (long val in item.Value.Distinct())
            {
                toWriteToTxt.AppendFormat("\t{0} * {1}\r\n", item.Value.Where(f => f == val).Count(),  // Amount of occurrencies of each number
                    val);
            }
        }
        // Writing the TXT
        using (FileStream fs = new FileStream(outputTxtPath, FileMode.Create))
        {
            using (StreamWriter sw = new StreamWriter(fs))
            {
                sw.Write(toWriteToTxt.ToString());
            }
        }
    }


    static string getFirstSheetName(OleDbConnection excelConnection)
    {
        using (DataTable ExcelTables = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" }))
        {
            return ExcelTables.Rows[0]["TABLE_NAME"].ToString();
        }
    }
}
}

.txt我希望看起来像这样:

|  A  |  B  |  C  |  D  |...
| Name|  1  |  2  |  3  |...
|  X  | 898 | 896 | 898 |...

基本上它的名称范围从A2到A n ,然后计算从B2到AF2的所有相同实例。最后我会得到一个txt文件,其中所有名称都有如上所列的列表。我也引用了Microsoft.Office.Interop.Excel,因为我读到它是必需的并找到this但是因为我是excel相关代码的新手我不知道我可以从那里使用什么作为应用程序的目的与我的有很大的不同。

如何使按钮执行上述功能?

我添加了codroipo给出的代码,现在我有了这些库:

 X:   4 * 898
      6 * 896

我也改变了using System; using System.Collections.Generic; using System.Data; using System.Data.OleDb; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes;

"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;", excelFilePath但我仍然在这里收到调试错误:

"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0;", excelFilePath

找不到类型或命名空间名称'FileStream'(您是否缺少using指令或程序集引用?)

// Writing the TXT using (FileStream fs = new FileStream(outputTxtPath, FileMode.Create)) { using (StreamWriter sw = new StreamWriter(fs)) { sw.Write(toWriteToTxt.ToString()); } } } static string getFirstSheetName(OleDbConnection excelConnection) { using (DataTable ExcelTables = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" })) { return ExcelTables.Rows[0]["TABLE_NAME"].ToString(); } } 字符串出错:

“预期的类,委托,枚举,接口或结构”

与下一行的 Object [] 一样。

我错过了一个图书馆吗?

1 个答案:

答案 0 :(得分:1)

我建议你在这种情况下使用Microsoft.Jet.OLEDB(如果你想要比较,请检查Which One is Best OLEDB Or Excel Object Or Database),这里有一些你可以使用的代码。我编写此代码假设您只想导出Excel中的第一个工作表:

    static void exportExcelToTxt(string excelFilePath, string outputTxtPath)
    {
        Dictionary<string, List<long?>> values = new Dictionary<string, List<long?>>();
        using (OleDbConnection excelConnection = new OleDbConnection(string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;", excelFilePath)))
        {
            excelConnection.Open();
            string firstSheet = getFirstSheetName(excelConnection);
            using (OleDbCommand cmd = excelConnection.CreateCommand())
            {
                cmd.CommandText = string.Format("SELECT * FROM [{0}]", firstSheet);
                using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
                {
                    using (DataTable dt = new DataTable())
                    {
                        da.Fill(dt); // Getting all the data in the sheet
                        foreach (DataRow item in dt.Rows)
                        {
                            List<long?> toAdd = new List<long?>();
                            string key = item[0] as string;
                            for (int i = 1; i < dt.Columns.Count; i++)
                            {
                                toAdd.Add(item[i] != DBNull.Value ? (long?)Convert.ToInt64(item[i]) : null);
                            }
                            values.Add(key, toAdd); // Associating all the "numbers" to the "Name"
                        }
                    }
                }
            }
        }
        StringBuilder toWriteToTxt = new StringBuilder();
        foreach (KeyValuePair<string, List<long?>> item in values)
        {
            // Formatting the output
            toWriteToTxt.Append(string.Format("{0}:", item.Key));
            foreach (long val in item.Value.Where(f => f != null).Distinct())
            {
                toWriteToTxt.AppendFormat("\t{0} * {1}\r\n", item.Value.Where(f => f == val).Count(),  // Amount of occurrencies of each number
                    val);
            }
        }
        // Writing the TXT
        using (FileStream fs = new FileStream(outputTxtPath, FileMode.Create))
        {
            using (StreamWriter sw = new StreamWriter(fs))
            {
                sw.Write(toWriteToTxt.ToString());
            }
        }
    }

    static string getFirstSheetName(OleDbConnection excelConnection)
    {
        using (DataTable ExcelTables = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" }))
        {
            return ExcelTables.Rows[0]["TABLE_NAME"].ToString();
        }
    }