【问题标题】:C# Excel to txt convert and format the output WPFC# Excel to txt 转换和格式化输出 WPF
【发布时间】:2015-05-25 09:30:48
【问题描述】:

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

我的代码如下所示:

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();
        }
    }
}
}

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

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

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

 X:   4 * 898
      6 * 896

基本上,它采用从 A2 到 An 的名称,然后计算从 B2 到 AF2 的所有相同实例。最后,我将有一个 txt 文件,其中所有名称都具有上述列表。我还引用了 Microsoft.Office.Interop.Excel,因为我阅读它是必需的,并找到了this,但由于我是 excel 相关代码的新手,我不知道我可以从那里使用什么作为应用程序的目的和我的很不一样。

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


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

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,但我仍然在这里遇到调试错误:

// 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();
    }
}

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

static string getFirstSheetName(OleDbConnection excelConnection)字符串有错误:

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

下一行的 Object[] 也是如此。

我错过了图书馆吗?

【问题讨论】:

  • “4 *”和“6 *”是898和896的出现次数?
  • 是的,这只是它如何显示特定地点数量的一个示例,这些数字对应于该人轮班的地点,因此它可能是餐厅 x 的 4 天和餐厅 y 的 6 天.
  • 对不起,这里需要用到using指令:using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.OleDb; using System.Data; using System.IO; FileStream的全称是System.IO.FileStream
  • 你能发布你试图编译的整个代码吗?我认为你可能有一些括号错误
  • 更新了我的代码,添加System.IO 解决了调试错误。这看起来应该有效吗?

标签: c# wpf excel


【解决方案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();
        }
    }

【讨论】:

  • 快速阅读 OLEDB 我得出的结论是,我可能应该使用 Microsoft.ACE.OLEDB.12.0,因为我正在运行 64 位系统,显然 Microsoft.Jet.oledb.4.0 仅适用于 32 位。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 2017-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-23
相关资源
最近更新 更多