【发布时间】:2017-06-29 15:10:45
【问题描述】:
我正在尝试从 excel / csv 文件中删除所有非 ascii 字符。在线阅读和搜索后,我发现一个帖子给了我代码xlWorksheet.UsedRange.Replace("[^\\u0000-\\u007F]" 以删除字符,但每次但字符仍然存在于文件中。
我也得到一个对话框说明
我们找不到可以替换的东西。单击选项以获取更多方法 搜索。
仅供参考:您尝试替换的数据可能位于受保护的 床单。 Excel 无法替换受保护工作表中的数据。
不确定如何继续。我一直在网上寻找和阅读,但到目前为止没有发现任何有用的东西。
感谢您的帮助。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\Users\username\Desktop\Error Records.csv");
Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int lastUsedRow = xlWorksheet.Cells.Find("*", System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value,
Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlPrevious,
false, System.Reflection.Missing.Value, System.Reflection.Missing.Value).Row;
int lastUsedColumn = xlWorksheet.Cells.Find("*", System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value,
Excel.XlSearchOrder.xlByColumns, Excel.XlSearchDirection.xlPrevious,
false, System.Reflection.Missing.Value, System.Reflection.Missing.Value).Column;
// int lastColumnCount = lastUsedColumn;
//;
// for (int i = 1; i <= lastUsedColumn; i++)
// {
// for (int j = 1; j <= lastUsedRow; j++)
// {
// xlWorksheet.Cells[j, (lastColumnCount+1)] = "Testing data 134";
// }
// }
xlWorksheet.Cells[1, (lastUsedColumn + 1)] = "Title";
xlWorksheet.UsedRange.Replace("[^\\u0000-\\u007F]", string.Empty);
xlWorkbook.Save();
//cleanup
GC.Collect();
GC.WaitForPendingFinalizers();
//rule of thumb for releasing com objects:
// never use two dots, all COM objects must be referenced and released individually
// ex: [somthing].[something].[something] is bad
//release com objects to fully kill excel process from running in the background
Marshal.ReleaseComObject(xlRange);
Marshal.ReleaseComObject(xlWorksheet);
//close and release
xlWorkbook.SaveAs("C:\\Users\\username\\Desktop\\Errors_four.csv".Trim(), Excel.XlFileFormat.xlCSV);
xlWorkbook.Close();
Marshal.ReleaseComObject(xlWorkbook);
//quit and release
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
}
}
}
【问题讨论】:
-
Excel 不支持正则表达式样式替换,因此您需要遍历每个单元格,将内容提取为字符串并对字符串进行替换并将其分配回单元格。