我试图抓取XLS电子表格中的单元格,将它们分配给字符串数组,然后操作数据并导出到多个CVS文件。
问题在于,XLS电子表格包含的信息与此无关,可使用的数据直到第17行才开始,而且列中只有默认的Sheet1才有标题。
我已经看过相关的问题,并试图自己找出,但没有成功。下面的读取XLS的代码可以工作,但是使用起来很麻烦,因为每个XLS文件的行长度不同,而且它会自动拉空列和行。
码
public static void xlsReader()
{
string fileName = string.Format("{0}\\LoadsAvailable.xls", Directory.GetCurrentDirectory());
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";" + @"Extended Properties='Excel 8.0;HDR=Yes;'";
string queryString = "SELECT * FROM [Sheet1$]";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
int counter = 0;
while (reader.Read())
{
Console.WriteLine("Line " + counter + ":" + reader[28].ToString()); // Just for testing
counter++;
}
}
}我可以用循环做一些技巧来获得所需的数据,但是必须有一个查询字符串,它可以从第17行获得数据,其中只有8列(而不是26列,18列为空)?
我尝试过许多查询字符串示例,无法让seam使用起始行索引或筛选出空数据。
发布于 2016-04-13 19:22:42
下面是一种方便的方法,可以将excel文件转换为平面文件。
您可能希望更改连接字符串属性以满足您的需要。我需要我的案子的头。
注意,您需要在计算机上安装Access数据库引擎。我需要32位版本,因为我开发的应用程序是32位。我打赌你也会需要它的。
我参数化了平面文件的分隔符,因为我在某些情况下不需要逗号,而需要管道符号。
如何调用ex:ConvertExcelToFlatFile(openFileName, savePath, '|'); // pipe delimited方法
// Converts Excel To Flat file
private void ConvertExcelToFlatFile(string excelFilePath, string csvOutputFile, char delimeter, int worksheetNumber = 1)
{
if (!File.Exists(excelFilePath)) throw new FileNotFoundException(excelFilePath);
if (File.Exists(csvOutputFile)) throw new ArgumentException("File exists: " + csvOutputFile);
// connection string
var cnnStr = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml; IMEX=1; HDR=NO\"", excelFilePath);
var cnn = new OleDbConnection(cnnStr);
// get schema, then data
var dt = new DataTable();
try
{
cnn.Open();
var schemaTable = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (schemaTable.Rows.Count < worksheetNumber) throw new ArgumentException("The worksheet number provided cannot be found in the spreadsheet");
string worksheet = schemaTable.Rows[worksheetNumber - 1]["table_name"].ToString().Replace("'", "");
string sql = String.Format("select * from [{0}]", worksheet);
var da = new OleDbDataAdapter(sql, cnn);
da.Fill(dt);
}
catch (Exception e)
{
throw e;
}
finally
{
// free resources
cnn.Close();
}
// write out CSV data
using (var wtr = new StreamWriter(csvOutputFile)) // disposes file handle when done
{
foreach (DataRow row in dt.Rows)
{
//MessageBox.Show(row.ItemArray.ToString());
bool firstLine = true;
foreach (DataColumn col in dt.Columns)
{
// skip the first line the initial
if (!firstLine)
{
wtr.Write(delimeter);
}
else
{
firstLine = false;
}
var data = row[col.ColumnName].ToString();//.Replace("\"", "\"\""); // replace " with ""
wtr.Write(String.Format("{0}", data));
}
wtr.WriteLine();
}
}
}https://stackoverflow.com/questions/36607200
复制相似问题