nam*_*los 30 c# csv excel clipboard diacritics
[STAThread]
static void Main(string[] args)
{
var fmt_csv = System.Windows.Forms.DataFormats.CommaSeparatedValue;
// read the CSV
var dataobject = System.Windows.Forms.Clipboard.GetDataObject();
var stream = (System.IO.Stream)dataobject.GetData(fmt_csv);
var enc = new System.Text.UTF8Encoding();
var reader = new System.IO.StreamReader(stream,enc);
string data_csv = reader.ReadToEnd();
// read the unicode string
string data_string = System.Windows.Forms.Clipboard.GetText();
}
Run Code Online (Sandbox Code Playgroud)
在查看评论并密切关注Excel在剪贴板上放置CSV之后,Excel可能会使用"遗留"编码而不是UTF-8来放置内容.所以我尝试使用Windows 1252代码页作为编码,它工作.请参阅下面的代码
[STAThread]
static void Main(string[] args)
{
var fmt_csv = System.Windows.Forms.DataFormats.CommaSeparatedValue;
//read the CSV
var dataobject = System.Windows.Forms.Clipboard.GetDataObject();
var stream = (System.IO.Stream)dataobject.GetData(fmt_csv);
var enc = System.Text.Encoding.GetEncoding(1252);
var reader = new System.IO.StreamReader(stream,enc);
string data_csv= reader.ReadToEnd();
//read the Unicode String
string data_string = System.Windows.Forms.Clipboard.GetText();
}
Run Code Online (Sandbox Code Playgroud)
Excel使用Unicode字符编码将字符串存储在剪贴板上.当您尝试读取ANSI中的字符串时,您获得正方形的原因是系统的ANSI代码页中没有该字符的表示.你应该只使用Unicode.如果你要处理本地化问题,那么ANSI就比它的价值更麻烦了.
编辑: Joel Spolsky写了一篇关于字符编码的精彩介绍,绝对值得一试:绝对最低每个软件开发人员绝对必须知道Unicode和字符集(没有借口!)
您将流编码为 UTF8 不起作用。元音变音的字节正在转换为“替换字符”unicode 字符。
相反,只需查看流的数据,无需任何额外的编码指令。数据将采用 Excel 使用的某种设定格式。您应该能够通过查看字节来判断 unlaut 所在的位置。然后您应该能够将其转换为 UTF-8。
最坏的情况是 CSV 格式化程序丢弃所有非 Ascii 字符。在这种情况下,您也许可以编写自己的数据格式化程序。
在某些情况下,Excel 人员认为 CSV 仅表示 Ascii。请参阅http://www.tech-archive.net/Archive/Excel/microsoft.public.excel.misc/2008-07/msg02270.html