我在服务器上有一个40列的XLS文件。
我需要将此XLS文件导出为CSV,但仅导出前五列,而不必导出其余的列。
我使用 Linq 尝试了此代码,但没有成功,因为CSV中的输出为空。
问题:我在做什么错?!
预先感谢您的帮助。
我的完整代码如下:
string filePath = HttpContext.Current.Server.MapPath(fileName.ToString());
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
DataSet result = excelReader.AsDataSet();
excelReader.Close();
result.Tables[0].TableName.ToString();
string csvData = "";
int row_no = 0;
int ind = 0;
while (row_no < result.Tables[ind].Rows.Count)
{
string s1 = "";
var columns = File
.ReadLines(filePath)
.SkipWhile(line => !string.IsNullOrWhiteSpace(line))
.FirstOrDefault()
.Split(new char[] { '\t', ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
List<string> expectedColumns = new List<string>() {
"AAA",
"BBB",
"CCC",
"DDD",
"EEE"};
if (expectedColumns.Except(columns, StringComparer.OrdinalIgnoreCase).Any())
{
// Some expected columns are not found; incorrect csv
}
else
{
for (int i = 0; i < result.Tables[ind].Columns.Count; i++)
{
s1 += result.Tables[ind].Rows[row_no][i].ToString() + "|";
}
if (s1.Length > 160)
{
csvData += s1;
}
}
row_no++;
csvData += "\n";
}
output = HttpContext.Current.Server.MapPath(DateTime.Now.ToString("dd-MM-yyyy") + ".csv");
newOutput = Path.GetFileName(output);
StreamWriter csv = new StreamWriter(@output, false);
csv.Write(csvData);
csv.Close();
csv.Dispose();