C#Excel到TXT转换和格式化输出WPF

我有一个WPF应用程序目前有2个button,一个用于select文件和一个将选定的文件转换为.txt格式。 现在我需要让另一个button读取excel文件并格式化数据并创build一个.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到A,然后从B2到AF2的所有相同的实例进行计数。 最后,我会有一个txt文件,所有的名字都像上面的列表。 我也有引用Microsoft.Office.Interop.Excel,因为我读它是必需的,发现这一点,但由于我是新的Excel相关的代码,我不知道我可以使用从那里作为应用程序的目的有很大的不同从我的。

我如何使button做一个如上所述的function?


我添加了由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但我仍然在这里得到debugging错误:

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

无法findtypes或名称空间名称“FileStream”(您是否缺lessusing指令或程序集引用?)

static string getFirstSheetName(OleDbConnection excelConnection) string有一个错误:

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

就像下一行的Object []一样

我错过了一个图书馆吗?

我build议你在这种情况下使用Microsoft.Jet.OLEDB(如果你想比较,请检查哪一个是最好的OLEDB或Excel对象或数据库 ),这里是一些你可以使用的代码。 我写了这个代码,假设你想要导出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(); } }