2 回答
TA贡献1828条经验 获得超6个赞
public class Program
{
public static void Main()
{
string filePath = "C:\\Users\\{User}\\Desktop\\sample.xlsx";
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
List<List<object>> rows = new List<List<object>>();
List<object> row = new List<object>();
// Excel Reader
using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream, new ExcelReaderConfiguration
{
FallbackEncoding = Encoding.GetEncoding(1252),
}))
{
do
{
while (reader.Read())
{
row.Clear();
for (int i = 0; i < reader.FieldCount; i++)
{
var field = reader.GetValue(i);
if (field is int valueInt)
{
row.Add(valueInt);
}
else if (field is bool valueBool)
{
row.Add(valueBool);
}
else if (field is DateTime valueDate)
{
//row.Add(valueDate); You can write any condition there
row.Add(valueDate.Year);
}
else if (field is TimeSpan valueTime)
{
row.Add(valueTime);
}
else if (field is string valueString)
{
row.Add(valueString);
}
else if (field is null)
{
row.Add(field);
}
}
if (row.Any())
{
rows.Add(row);
}
}
} while (reader.NextResult());
}
}
// CSV Writer
using (var writer = new StreamWriter("C:\\Users\\{User}\\Desktop\\sample.csv"))
using (var csv = new CsvWriter(writer))
{
foreach (var i in rows)
{
foreach (var field in i)
{
csv.WriteField(field);
}
csv.NextRecord();
}
}
}
}
该程序将 Excel (sample.xlsx) 文件转换为 CSV(sample.csv) 文件。
TA贡献1856条经验 获得超17个赞
创建一个类文件,其中包含与 Excel 列相同的属性。解析您的 Excel 文件并将其加载到您的类的实例中。写一个简单的程序如下
void Main()
{
var records = new List<Foo>
{
new Foo { Id = 1, Name = "one" },
};
using (var writer = new StreamWriter("path\\to\\file.csv"))
using (var csv = new CsvWriter(writer))
{
csv.WriteRecords(records);
}
}
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
其中 Foo 是类文件。希望这可以帮助
- 2 回答
- 0 关注
- 198 浏览
添加回答
举报