[英]C# Excel to txt convert and format the output WPF
我有一個WPF應用程序,當前有2個按鈕,一個用於選擇文件,一個用於將所選文件轉換為.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到A n的名稱,然后計算從B2到AF2的所有相同實例。 最后,我將得到一個txt文件,其中所有名稱都具有上述列表。 我還參考了Microsoft.Office.Interop.Excel,因為我讀到它是必需的,卻發現了這一點,但是由於我是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 []一樣 。
我想念圖書館嗎?
我建議您在這種情況下使用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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.