C# 有没有简单的方法将.xls文件转换为.csv文件?(Excel)
有没有简单的方法将.xls文件转换为.csv文件?胜过 用C代码 我的意思是将现有的.xls文件转换成.csv文件 提前感谢在Excel对象中签出该方法C# 有没有简单的方法将.xls文件转换为.csv文件?(Excel),c#,excel,csv,C#,Excel,Csv,有没有简单的方法将.xls文件转换为.csv文件?胜过 用C代码 我的意思是将现有的.xls文件转换成.csv文件 提前感谢在Excel对象中签出该方法 wbWorkbook.SaveAs("c:\yourdesiredFilename.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV) 或以下各项: public static void SaveAs() { Microsoft.Office.Interop.Excel.A
wbWorkbook.SaveAs("c:\yourdesiredFilename.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV)
或以下各项:
public static void SaveAs()
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook wbWorkbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel.Sheets wsSheet = wbWorkbook.Worksheets;
Microsoft.Office.Interop.Excel.Worksheet CurSheet = (Microsoft.Office.Interop.Excel.Worksheet)wsSheet[1];
Microsoft.Office.Interop.Excel.Range thisCell = (Microsoft.Office.Interop.Excel.Range)CurSheet.Cells[1, 1];
thisCell.Value2 = "This is a test.";
wbWorkbook.SaveAs(@"c:\one.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wbWorkbook.SaveAs(@"c:\two.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVWindows, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wbWorkbook.Close(false, "", true);
}
这里有一个C方法来实现这一点。请记住添加您自己的错误处理-这主要是假设为了简洁起见,事情可以正常工作。它只是4.0+框架,但这主要是因为可选的worksheetNumber参数。如果需要支持早期版本,可以重载该方法
static void ConvertExcelToCsv(string excelFilePath, string csvOutputFile, 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.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;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)) {
foreach (DataRow row in dt.Rows) {
bool firstLine = true;
foreach (DataColumn col in dt.Columns) {
if (!firstLine) { wtr.Write(","); } else { firstLine = false; }
var data = row[col.ColumnName].ToString().Replace("\"", "\"\"");
wtr.Write(String.Format("\"{0}\"", data));
}
wtr.WriteLine();
}
}
}
我需要做同样的事情。我最终得到了和凯曼相似的东西
static void ExcelToCSVCoversion(string sourceFile, string targetFile)
{
Application rawData = new Application();
try
{
Workbook workbook = rawData.Workbooks.Open(sourceFile);
Worksheet ws = (Worksheet) workbook.Sheets[1];
ws.SaveAs(targetFile, XlFileFormat.xlCSV);
Marshal.ReleaseComObject(ws);
}
finally
{
rawData.DisplayAlerts = false;
rawData.Quit();
Marshal.ReleaseComObject(rawData);
}
Console.WriteLine();
Console.WriteLine($"The excel file {sourceFile} has been converted into {targetFile} (CSV format).");
Console.WriteLine();
}
如果有多张图纸,则在转换过程中会丢失,但您可以循环查看图纸的数量,并将每个图纸保存为csv 安装这两个软件包
<packages>
<package id="ExcelDataReader" version="3.3.0" targetFramework="net451" />
<package id="ExcelDataReader.DataSet" version="3.3.0" targetFramework="net451" />
</packages>
我集成了@mattmc3 aswer。如果要转换xlsx文件,应使用此连接字符串。matt提供的字符串适用于xls格式,而不是xlsx:
这是对nate_weldon答案的修改,但有一些改进: Excel对象的更健壮发布 设置application.DisplayAlerts=false;在尝试保存之前,请先隐藏提示 还要注意,application.Workbooks.Open和ws.SaveAs方法期望sourceFilePath和targetFilePath是完整路径,即目录路径+文件名
private static void SaveAs(string sourceFilePath, string targetFilePath)
{
Application application = null;
Workbook wb = null;
Worksheet ws = null;
try
{
application = new Application();
application.DisplayAlerts = false;
wb = application.Workbooks.Open(sourceFilePath);
ws = (Worksheet)wb.Sheets[1];
ws.SaveAs(targetFilePath, XlFileFormat.xlCSV);
}
catch (Exception e)
{
// Handle exception
}
finally
{
if (application != null) application.Quit();
if (ws != null) Marshal.ReleaseComObject(ws);
if (wb != null) Marshal.ReleaseComObject(wb);
if (application != null) Marshal.ReleaseComObject(application);
}
}
谢谢你的帮助,但是我怎样才能转换一个现有的文件呢?如果你还在想,您需要首先使用Excel.Application.Workbooks.open方法将现有文件作为工作簿打开,并将其用作WB工作簿参数使用xlSaveAsAccessMode.xlNoChange更可靠如果使用xlShared,则调用SaveAs会崩溃。我发现此答案中确实存在缺陷。如果有外文汉字等,则必须将第二个参数设置为XlUnicodeText。这允许您保留字符,但会丢失CSV格式。它将其保存为以制表符分隔的。在接近尾端的地方有一个参数,您可以在其中设置代码页,但是在浏览互联网时,似乎没有人知道如何使其工作。互操作类型“ApplicationClass”无法嵌入?只需将“ApplicationClass”替换为“Application”。我尝试使用这个库,但遇到了一个拦截器,在这里提出:ExcelDataReader对我来说非常有用,如果要将大型Excel文件转换为CSV,我建议您避免使用AsDataSet将整个数据集读取到内存中,而是逐行读取数据,并在不将大量数据存储在内存中的情况下管理输出。一个很好的例子是如何做到这一点位于他们的维基这里非常感谢这个伟大的功能。我有一个XLSX格式的日期,2018年8月10日,出于某种原因,当我将其转换为CSV格式时,它也插入了一个时间,2018年8月10日12:00:00AM,我试图通过设置UseColumnDataType=false来攻击它,这就产生了同样的ResultAft问题——如果您有多张工作表,会发生什么?了解程序集引用会很有帮助
var excelFilePath = Console.ReadLine();
string output = Path.ChangeExtension(excelFilePath, ".csv");
ExcelFileHelper.SaveAsCsv(excelFilePath, output);
var cnnStr = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO\"", excelFilePath);
private static void SaveAs(string sourceFilePath, string targetFilePath)
{
Application application = null;
Workbook wb = null;
Worksheet ws = null;
try
{
application = new Application();
application.DisplayAlerts = false;
wb = application.Workbooks.Open(sourceFilePath);
ws = (Worksheet)wb.Sheets[1];
ws.SaveAs(targetFilePath, XlFileFormat.xlCSV);
}
catch (Exception e)
{
// Handle exception
}
finally
{
if (application != null) application.Quit();
if (ws != null) Marshal.ReleaseComObject(ws);
if (wb != null) Marshal.ReleaseComObject(wb);
if (application != null) Marshal.ReleaseComObject(application);
}
}