我已经有了从.xls转换为.txt的代码。但问题是,它只导出一行并停止。我需要为代码添加什么来读取所有行并将其转换为txt文件?
这是我的代码:
using (OleDbConnection cn = new OleDbConnection())
{
using (OleDbCommand cmd = new OleDbCommand())
{
cn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + @"C:\Users\jediablaza\Documents\EDIExcel\EDIExcel.xls" + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";";
cmd.Connection = cn;
cmd.CommandText = "SELECT * from [Sheet1$]";
using (OleDbDataAdapter adp = new OleDbDataAdapter(cmd))
{
DataTable dt = new DataTable();
adp.Fill(dt);
using (StreamWriter wr = new StreamWriter(@"C:\Users\jediablaza\Documents\EDIExcel\EDIExcel.txt"))
{
foreach (DataRow row in dt.Rows)
{
wr.WriteLine(row[0] + "\t" + row[1] + "\t" + row[2] + "\t" + row[3] + "\t" + row[4]);
}
}
}
}
}
文本的输出显示在下面
SHARPDTL TESTDTL1 TESTDTL2 TESTDTL3 TESTDTL4
但是excel文件内容是
SHARPHDR1 TESTDHR1 TESTHDR2 TESTHDR3 TESTHDR4
SHARPDTL TESTDTL1 TESTDTL2 TESTDTL3 TESTDTL4
答案 0 :(得分:5)
我认为问题出在您的连接属性中:HDR=Yes
。
所以第一行是文件的标题。
将其更改为HDR=No
" HDR =是;"表示第一行包含列名,而不是 数据。 " HDR =无;"表明相反。
参考链接:excel connection
答案 1 :(得分:1)
显然你的问题是你在foreach
循环中使用固定索引。
我试图在下一个块中修复你的代码,我无法保证它会在我的手机上运行,只能用作参考。
using (OleDbConnection cn = new OleDbConnection())
{
using (OleDbCommand cmd = new OleDbCommand())
{
cn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + @"C:\Users\jediablaza\Documents\EDIExcel\EDIExcel.xls" + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";";
cmd.Connection = cn;
cmd.CommandText = "SELECT * from [Sheet1$]";
using (OleDbDataAdapter adp = new OleDbDataAdapter(cmd))
{
DataTable dt = new DataTable();
adp.Fill(dt);
using (StreamWriter wr = new StreamWriter(@"C:\Users\jediablaza\Documents\EDIExcel\EDIExcel.txt"))
{
foreach (DataRow row in dt.Rows)
{
var strBldr = new StringBuilder();
foreach (var col in row.Columns)
{
strBldr.Append("{col}\t");
}
wr.WriteLine(strBldr);
}
}
}
}
}