[英]C# Excel to txt convert and format the output WPF
I have a WPF application with 2 buttons currently, one for choosing the file and one to convert the chosen file to .txt format. 我有一个WPF应用程序,当前有2个按钮,一个用于选择文件,一个用于将所选文件转换为.txt格式。 Now I need to make the other button read the excel file and format the data and make a .txt file.
现在,我需要使另一个按钮读取excel文件并格式化数据并创建一个.txt文件。
My code looks like this: 我的代码如下所示:
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 files I will be using this on will look like this: 我将在其上使用的Excel文件将如下所示:
| A | B | C | D |...
| Name| 1 | 2 | 3 |...
| X | 898 | 896 | 898 |...
And the .txt I would like to look like this: .txt我想看起来像这样:
X: 4 * 898
6 * 896
Basically so it takes the name ranging from A2 to A n and then count all the identical instances from B2 to AF2. 基本上,因此它使用从A2到A n的名称,然后计算从B2到AF2的所有相同实例。 And in the end I would have a txt file with all the names having lists like above.
最后,我将得到一个txt文件,其中所有名称都具有上述列表。 I also have referenced Microsoft.Office.Interop.Excel, as I read it is required and found this but as I am new to excel related code I have no idea what I can use from there as the purpose of the application there is very different from mine.
我还参考了Microsoft.Office.Interop.Excel,因为我读到它是必需的,却发现了这一点,但是由于我是excel相关代码的新手,所以我不知道我可以从那里使用什么作为应用程序的用途,这有很大的不同从我的。
How can I make the button do a function as described above? 如何使按钮具有上述功能?
I added the code given by codroipo and now I have these libraries: 我添加了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;
I also changed "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;", excelFilePath
我还更改了
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;", excelFilePath
to "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0;", excelFilePath
but I still get debug errors here: 到
"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();
}
}
The type or namespace name 'FileStream' could not be found(are you missing a using directive or an assembly reference?) 找不到类型或名称空间名称“ FileStream”(是否缺少using指令或程序集引用?)
static string getFirstSheetName(OleDbConnection excelConnection)
the string has an error: static string getFirstSheetName(OleDbConnection excelConnection)
字符串有错误:
"Expected class, delegate, enum, interface, or struct" “预期的类,委托,枚举,接口或结构”
as does the Object[] on the next row. 就像下一行的Object []一样 。
Am I missing a library? 我想念图书馆吗?
I suggest you to use Microsoft.Jet.OLEDB in this case(if you want a comparison please check Which One is Best OLEDB Or Excel Object Or Database ), here is a some code that you can use. 我建议您在这种情况下使用Microsoft.Jet.OLEDB(如果要进行比较,请检查“ 哪个是最好的OLEDB或Excel对象或数据库” ),以下是一些可以使用的代码。 I wrote this code assuming that you want to export just the first sheet in the 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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.