我有一个包含公式的excel文件。公式使用一些需要第三方添加的函数。我试图使用C#中的以下代码将excel文件保存为csv。但公式字段显示为错误。如何将公式字段保存为值,然后将其保存在csv中。
public static void SaveExcelFileAsCsvAllSheets(string fileName)
{
var app = new Microsoft.Office.Interop.Excel.Application();
try
{
Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Open(fileName);
app.DisplayAlerts = false;
app.ScreenUpdating = false;
int sheetCount = 1;
foreach (Microsoft.Office.Interop.Excel.Worksheet sht in wb.Worksheets)
{
if (sht.Visible == XlSheetVisibility.xlSheetVisible)
{
sht.Select();
wb.SaveAs(Path.GetDirectoryName(fileName) + @"\" + Path.GetFileNameWithoutExtension(fileName) + "-" + sheetCount.ToString() + ".csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV, AccessMode: XlSaveAsAccessMode.xlNoChange);
sheetCount++;
}
}
wb.Close(false);
app.DisplayAlerts = true;
app.ScreenUpdating = true;
}
catch (Exception ex)
{
throw;
}
finally
{
app.Quit();
}
}
答案 0 :(得分:2)
选择包含数据的范围,然后将值复制并粘贴到位:
using Excel = Microsoft.Office.Interop.Excel;
Excel.Range targetRange = (Excel.Range)CurrentSheet.UsedRange;
targetRange.Copy(Type.Missing);
targetRange.Paste(Excel.XlPasteType.xlPasteValues,
Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);