C#导出Excel按照指定格式设置单元格属性值

转自:http://blog.csdn.net/u011981242/article/details/51544571

最近项目中一直在写XML、Table、Excel之间的转化。之前一直都是不考虑格式的导出,今天给出一个格式,让按照格式导出,还真把我这新手为难了一翻,网上给出的资料基本一样。为了一个单元格文字变色纠结了很久。下面把学习资料发出,希望对新手学习有所帮助:

下面是会用到的导出属性。

合并单元格属性:

[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. worksheet.get_Range(worksheet.Cells[rowIndex, columnCount + 1], worksheet.Cells[rowIndex + 2, columnCount + 1]).MergeCells = true;  
设置某一个单元格中字体的颜色:
[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. worksheet.get_Range(worksheet.Cells[rowIndex, 5], worksheet.Cells[rowIndex, 8]).Font.ColorIndex = 5;//这个在网上找的一直变不了色,后面自己试出来了  
字体颜色的index值:
C#导出Excel按照指定格式设置单元格属性值
选定区间设置字符串格式或数字格式:
[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. Microsoft.Office.Interop.Excel.Range range = worksheet.get_Range(worksheet.Cells[rowIndex, 1], worksheet.Cells[rowCount+rowIndex-1, columnCount-1]);  
  2.             range.NumberFormat = "@";//设置数字文本格式  
  3.             Microsoft.Office.Interop.Excel.Range rangeinfo = worksheet.get_Range(worksheet.Cells[rowIndex, 4], worksheet.Cells[rowCount + rowIndex - 1, 4]);  
  4.             rangeinfo.NumberFormat = "00";  
用于汇总和计算时(所计算的字段值必须是数字格式):
[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. worksheet.Cells[rowIndex + i, columnCount+1] = "=CEILING(D" + (rowIndex + i).ToString() + "*1.01+1,2)";  //i是变量  

-------------------------------------------------------------------
PS:以下代码则可导出如下图的Excel格式:
C#导出Excel按照指定格式设置单元格属性值

[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /// 导出为Excel格式文件  
  2.        /// </summary>  
  3.        /// <param name="dt">作为数据源的DataTable</param>  
  4.        /// <param name="saveFile">带路径的保存文件名</param>  
  5.        /// <param name="title">一个Excel sheet的标题</param>  
  6.        public static void DataTabletoExcel(System.Data.DataTable dt, string saveFile)  
  7.        {  
  8.           Microsoft.Office.Interop.Excel.Application rptExcel = new Microsoft.Office.Interop.Excel.Application();  
  9.            if (rptExcel == null)  
  10.            {  
  11.                PublicClass.HintBox("无法打开EXcel,请检查Excel是否可用或者是否安装好Excel");  
  12.                return;  
  13.            }  
  14.   
  15.            int rowCount = dt.Rows.Count;//行数  
  16.            int columnCount = dt.Columns.Count;//列数  
  17.            int rowIndex = 1;  
  18.            int colindex = 1;  
  19.            //保存文化环境  
  20.            System.Globalization.CultureInfo currentCI = System.Threading.Thread.CurrentThread.CurrentCulture;  
  21.            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");  
  22.   
  23.            Microsoft.Office.Interop.Excel.Workbook workbook = rptExcel.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);  
  24.            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets.get_Item(1);  
  25.            worksheet.Name = "报表";//一个sheet的名称  
  26.            rptExcel.Visible = true;//打开导出的Excel文件  
  27.   
  28.            worksheet.Cells[1, 1] = "27705";//模版号  
  29.            rowIndex++;  
  30.            //第二行内容  
  31.            Microsoft.Office.Interop.Excel.Range rangeinfo1 = worksheet.get_Range(worksheet.Cells[rowIndex, colindex + 6],worksheet.Cells[rowIndex, colindex + 7]);  
  32.            rangeinfo1.NumberFormat = "@";  
  33.            worksheet.Cells[rowIndex, colindex] = "S#262229";  
  34.            worksheet.Cells[rowIndex, colindex+6] = dt.Columns[13].ColumnName;  
  35.            worksheet.Cells[rowIndex, colindex + 7] = dt.Rows[0][13];  
  36.            worksheet.Cells[rowIndex, colindex+12] = "EAN";  
  37.            //合并打印数量单元格  
  38.            worksheet.Cells[rowIndex, columnCount+1] = "打印数量";  
  39.            worksheet.Cells[rowIndex, columnCount+2] = "包装数量";  
  40.            worksheet.get_Range(worksheet.Cells[rowIndex, columnCount + 1], worksheet.Cells[rowIndex + 2, columnCount + 1]).MergeCells = true;  
  41.            worksheet.get_Range(worksheet.Cells[rowIndex, columnCount + 2], worksheet.Cells[rowIndex + 2, columnCount + 2]).MergeCells = true;  
  42.            rowIndex++;  
  43.            //第三行内容  
  44.            worksheet.Cells[rowIndex, 1] = "貨名";  
  45.            worksheet.Cells[rowIndex, 2] = "Line";  
  46.            //合并第三行第二列  
  47.            worksheet.get_Range(worksheet.Cells[rowIndex, 2], worksheet.Cells[rowIndex+1, 2]).MergeCells = true;  
  48.            worksheet.Cells[rowIndex, 3] = "序號";  
  49.            worksheet.Cells[rowIndex, 4] = "數量";  
  50.            worksheet.Cells[rowIndex, 5] = "1 (EUR) size";  
  51.            worksheet.Cells[rowIndex, 6] = "1a (€)";  
  52.            worksheet.Cells[rowIndex, 7] = "2 (UK) size";  
  53.            worksheet.Cells[rowIndex, 8] = "2a (₤)";  
  54.            worksheet.get_Range(worksheet.Cells[rowIndex, 5], worksheet.Cells[rowIndex, 8]).Font.Bold = true;  
  55.            worksheet.Cells[rowIndex, 9] = "4";  
  56.            worksheet.Cells[rowIndex, 10] = "5";  
  57.            worksheet.Cells[rowIndex, 11] = "6";  
  58.            worksheet.Cells[rowIndex, 12] = "7";  
  59.            worksheet.Cells[rowIndex, 13] = "8(barcode)";  
  60.            worksheet.Cells[rowIndex, 14] = "9";  
  61.            worksheet.get_Range(worksheet.Cells[rowIndex, 5], worksheet.Cells[rowIndex, 8]).Font.ColorIndex = 5;  
  62.            rowIndex++;  
  63.            //填充列标题  
  64.            for (int i = 0; i < columnCount-1; i++)  
  65.            {  
  66.                if (i > 0)  
  67.                {  
  68.                    worksheet.Cells[rowIndex, i + 2] = dt.Columns[i].ColumnName;  
  69.                     
  70.   
  71.                }  
  72.                else  
  73.                {  
  74.                    worksheet.Cells[rowIndex, i+1] = dt.Columns[i].ColumnName;  
  75.                      
  76.                }  
  77.            }  
  78.            rowIndex++;  
  79.             
  80.            //创建对象数组存储DataTable的数据,这样的效率比直接将Datateble的数据填充worksheet.Cells[row,col]高  
  81.            object[,] objData = new object[rowCount, columnCount];  
  82.             
  83.            //填充内容到对象数组  
  84.            for (int r = 0; r < rowCount; r++)  
  85.            {  
  86.                for (int col = 0; col < columnCount-1; col++)  
  87.                {  
  88.                    objData[r, col] = dt.Rows[r][col].ToString();  
  89.                }  
  90.   
  91.                System.Windows.Forms.Application.DoEvents();  
  92.            }  
  93.             
  94.              
  95.            //将对象数组的值赋给Excel对象  
  96.            Microsoft.Office.Interop.Excel.Range range = worksheet.get_Range(worksheet.Cells[rowIndex, 1], worksheet.Cells[rowCount+rowIndex-1, columnCount-1]);  
  97.            range.NumberFormat = "@";//设置数字文本格式  
  98.            Microsoft.Office.Interop.Excel.Range rangeinfo = worksheet.get_Range(worksheet.Cells[rowIndex, 4], worksheet.Cells[rowCount + rowIndex - 1, 4]);  
  99.            rangeinfo.NumberFormat = "00";  
  100.            range.Value2 = objData;  
  101.   
  102.            for (int i = 0; i < rowCount; i++)  
  103.            {  
  104.                if (i > 0)  
  105.                {  
  106.                      
  107.                    //计算打印数量  
  108.                    worksheet.Cells[rowIndex + i, columnCount+1] = "=CEILING(D" + (rowIndex + i).ToString() + "*1.01+1,2)";  
  109.   
  110.                }  
  111.                else  
  112.                {  
  113.                     
  114.                    worksheet.Cells[rowIndex + i, columnCount+1] = "=CEILING(D" + (rowIndex + i).ToString() + "*1.01+1,2)";  
  115.                }  
  116.            }  
  117.              
  118.            //设置格式  
  119.            rptExcel.StandardFont = "新細明體";  
  120.            rptExcel.StandardFontSize = 12;  
  121.            worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[rowCount+rowIndex, columnCount]).Columns.AutoFit();//设置单元格宽度为自适应  
  122.            worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[rowCount+rowIndex, columnCount]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;//居中对齐  
  123.            //worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[1, columnCount]).Font.Bold = true;  
  124.            //worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[1, columnCount]).Font.Color= ConsoleColor.Blue;  
  125.           // worksheet.get_Range(worksheet.Cells[2, 1], worksheet.Cells[rowCount + 2, columnCount]).Borders.LineStyle = 1;//设置边框  
  126.           //汇总  
  127.            rowIndex = rowCount + rowIndex;  
  128.            worksheet.Cells[rowIndex, 4] = "=SUM(D5:D10)";  
  129.             
  130.              
  131.            //恢复文化环境  
  132.            System.Threading.Thread.CurrentThread.CurrentCulture = currentCI;  
  133.            try  
  134.            {  
  135.                //rptExcel.Save(saveFile); //自动创建一个新的Excel文档保存在“我的文档”里,如果不用SaveFileDialog就可用这种方法  
  136.                workbook.Saved=true;  
  137.                workbook.SaveCopyAs(saveFile);//以复制的形式保存在已有的文档里  
  138.                PublicClass.HintBox("数据已经成功导出为Excel文件!");  
  139.            }  
  140.            catch (Exception ex)  
  141.            {  
  142.                PublicClass.HintBox("导出文件出错,文件可能正被打开,具体原因:" + ex.Message);  
  143.            }  
  144.            finally  
  145.            {  
  146.                dt.Dispose();  
  147.                rptExcel.Quit();  
  148.               System.Runtime.InteropServices.Marshal.ReleaseComObject(rptExcel);  
  149.               System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);  
  150.               System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);  
  151.                GC.Collect();  
  152.                KillAllExcel();  
  153.            }  
  154.        }  
  155.        /// <summary>  
  156.        /// 获得所有的Excel进程  
  157.        /// </summary>  
  158.        /// <returns>所有的Excel进程</returns>  
  159.        private static List<Process> GetExcelProcesses()  
  160.            {  
  161.            Process[] processes = Process.GetProcesses();  
  162.            List<Process> excelProcesses = new List<Process>();  
  163.   
  164.            for (int i = 0; i < processes.Length; i++)  
  165.            {  
  166.                if (processes[i].ProcessName.ToUpper() == "EXCEL")  
  167.                    excelProcesses.Add(processes[i]);  
  168.            }  
  169.   
  170.            return excelProcesses;   
  171.        }  
  172.        private static void KillAllExcel()  
  173.        {  
  174.            List<Process> excelProcess = GetExcelProcesses();  
  175.            for (int i = 0; i < excelProcess.Count; i++)  
  176.            {  
  177.                excelProcess[i].Kill();  
  178.            }  
  179.        }  

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值