Excel格式問題的處理

問題

  1. Excel中的日期自動變成整數
  2. 設置的邊框等格式在重新打開後消失
  3. 操作反應變慢

原因分析

在Excel中多次的複製粘貼、修改樣式會不斷積累許多單元格的樣式設置,當樣式過多時就可能出現混亂的情況。

解決辦法

經過實踐,可以將樣式刪除後重新設置格式即可恢復正常。但普通的刪除方法通過遍歷處理可能會非常的慢,比如以下的代碼,通過VBA來處理,有些文檔樣式幾百上千個的時候慢得很:

Application.ScreenUpdating=False
Dim mystyle As Style
On Error Resume Next
For Each mystyle In ActiveWorkbook.Styles
    If mystyle.BuiltIn = False Then mystyle.Delete
Next
Application.ScreenUpdating=True

2007及以後的版本文件都是一個壓縮包,裏面包含了各種文件,其中就有一個styles.xml文件,裏面保存了工作表的各種樣式,只要將其刪除掉就可以了。思路就是將文件保存爲xlsx格式,然後解壓,再找到styles.xml,刪除樣式。

C#處理的代碼:

            string excelpath = txtInputFile.Text;//這裏用文件選擇框選擇賦值
            if (File.Exists(excelpath))
            {
                txtOutFilePath.Text = "";
                btnOpenFile.Enabled = false;
                try
                {
                    FileInfo fileinfo = new FileInfo(excelpath);

                    string newFileName = fileinfo.FullName.Substring(0, fileinfo.FullName.Length - fileinfo.Extension.Length) + "_noStyle" + fileinfo.Extension;
                    //newFileName是另存的文件名
                    string bakPath = fileinfo.Directory.ToString() + @"\Tmp";
                    //備份
                    File.Copy(excelpath, newFileName);
                    //解壓
                    (new FastZip()).ExtractZip(newFileName, bakPath, "");
                    //替換Styles
                    string xmlPath = bakPath + @"\xl\styles.xml";
                    string style = File.ReadAllText(xmlPath, Encoding.UTF8);
                    Regex regex = new Regex(@"<cellStyles.*</cellStyles>", RegexOptions.IgnoreCase);
                    string result = regex.Replace(style, "");
                    File.WriteAllText(xmlPath, result, Encoding.UTF8);
                    //壓縮
                    (new FastZip()).CreateZip(newFileName, bakPath, true, "");

                    //刪除文件夾
                    DirectoryInfo di = new DirectoryInfo(bakPath);
                    di.Delete(true);
                    txtOutFilePath.Text = newFileName;
                    btnOpenFile.Enabled = true;
                    MessageBox.Show("刪除成功!\n\n刪除樣式後的文件:" + newFileName, "溫馨提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message, "溫馨提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("文件不存在!", "溫馨提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

這樣處理的話速度快很多。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章