1.引入命名空间
using System.Reflection;
using Microsoft.Office.Interop.Excel;
using System.Diagnostics;
2.主体代码如下:
Microsoft.Office.Interop.Excel.Application myExcel = new Microsoft.Office.Interop.Excel.Application();
Workbook myWorkbook = null;
Worksheet mySheet = null;
try
{
string str1 = System.Environment.CurrentDirectory;
string str = System.IO.Directory.GetCurrentDirectory();
string excelFileName = str + "\\DataTest.xlsx";
string newFileName = str + "\\new1.xlsx";
FileInfo fi = new FileInfo(excelFileName);
if (!fi.Exists) MessageBox.Show("模板文件不存在");//判断文件是否已经存在
FileInfo fi2 = new FileInfo(newFileName);
if (fi2.Exists) fi2.Delete();
// 打开Excel文件
myWorkbook = myExcel.Workbooks.Open(excelFileName, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
// 获取第一个sheet
mySheet = (Worksheet)myWorkbook.Sheets[1];
//mySheet.Cells[9, 9] = "ABC";//写数据
//mySheet.Cells[9, 10] = "=SUM(C3:C6)";//"使用公式";
mySheet.Cells[12, 4].NumberFormatLocal = "0";//数字格式 各种格式参考EXCEL设置单元格格式的自定义查看
for (int i = 7; i < 16; i++)
{
for (int j = 1; j < 10; j++)
{
mySheet.Cells[i, j] = "item"+i+j;
}
if (i % 2 == 0) continue;
mySheet.Rows[2, Missing.Value].Copy(mySheet.Rows[i+1, Missing.Value]);//复制整行包含格式样式
}
#region 隐藏行和隐藏列
//mySheet.get_Range((Range)mySheet.Cells[19, 1], (Range)mySheet.Cells[22, 1]).EntireRow.Hidden = true;
//mySheet.get_Range((Range)mySheet.Cells[1, 1], (Range)mySheet.Cells[mySheet.Rows.Count, 1]).EntireColumn.Hidden = true;
#endregion
#region 取得单元格下拉框域的值
//string strValue = ((Range)mySheet.Cells[3, 10]).Validation.Formula1;
//MessageBox.Show(strValue);
#endregion
#region 关于单元格设置域和取得域里需要的数据--先增加再修改如果已有不需增加只修改
//增加单元格下拉框的数据
//((Range)mySheet.Cells[3, 10]).Validation.Add(XlDVType.xlValidateList, XlDVAlertStyle.xlValidAlertStop, Type.Missing, "1,2,3", Type.Missing);
//修改已有单元格下拉框的数据
//((Range)mySheet.Cells[3, 10]).Validation.Modify(XlDVType.xlValidateList, XlDVAlertStyle.xlValidAlertStop, Type.Missing, "2,2,3", Type.Missing);
#endregion
#region 屏蔽掉系统跳出的Alert(文件保存提示是否保存什么的)
//myExcel.AlertBeforeOverwriting = false;
#endregion
#region 指定区域的复制
//Range range12 = mySheet.get_Range((Range)mySheet.Cells[7, 1], (Range)mySheet.Cells[11, mySheet.Columns.Count]);
//range12.Select();
选中粘贴的起始位置
//Range test = ((Range)mySheet.Cells[19, 1]);
//range12.Copy(test);
#endregion
#region 设置边框的上、下、左、右线条
//mySheet.get_Range((Range)mySheet.Cells[7, 1], (Range)mySheet.Cells[12, 3]).Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick; //左
//mySheet.get_Range((Range)mySheet.Cells[7, 1], (Range)mySheet.Cells[12, 3]).Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;//右
//mySheet.get_Range((Range)mySheet.Cells[7, 1], (Range)mySheet.Cells[12, 3]).Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThick;//上
//mySheet.get_Range((Range)mySheet.Cells[7, 1], (Range)mySheet.Cells[12, 3]).Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;//下
#endregion
#region //设置单元格颜色 颜色共有56中
((Range)mySheet.Rows[1, Missing.Value]).Interior.ColorIndex = 3;
//mySheet.get_Range((Range)mySheet.Cells[2, 1], (Range)mySheet.Cells[10, 10]).Interior.ColorIndex = 3;//指定区域设定颜色
#endregion
#region 设置行高和列宽
//设置行高和列宽
//mySheet.Rows[3, Missing.Value].RowHeight = 35;
//((Range)mySheet.Rows[3, Missing.Value]).ColumnWidth = 35;
#endregion
#region 插入一列
//mySheet.get_Range("B1", "B" + mySheet.Rows.Count).Insert(Missing.Value, XlInsertShiftDirection.xlShiftToRight);
//mySheet.get_Range((Range)mySheet.Cells[1, 2], (Range)mySheet.Cells[mySheet.Rows.Count, 2]).Insert(Missing.Value, XlInsertShiftDirection.xlShiftToRight);
#endregion
#region 插入一行
//((Range)mySheet.Rows[11, Missing.Value]).Insert(Missing.Value, XlInsertFormatOrigin.xlFormatFromLeftOrAbove);
#endregion
#region 删除整行及范围格式样式文字
//((Range)mySheet.Rows[16, Missing.Value]).Delete(XlDeleteShiftDirection.xlShiftUp);//删除整行
//mySheet.get_Range("B3", "V17").Delete(XlDeleteShiftDirection.xlShiftToLeft);//删除范围
//mySheet.get_Range((Range)mySheet.Cells[1, 2], (Range)mySheet.Cells[mySheet.Rows.Count, 2]).Delete(XlDeleteShiftDirection.xlShiftToLeft);
#endregion
#region 格式设定
//全表自动列宽
//mySheet.Cells.Select();
//mySheet.Cells.Columns.AutoFit();
//设置区域边框
//((Range)mySheet.Cells[3, 3]).Borders.LineStyle = 3;
//粗体设置
//mySheet.get_Range("A2", "V2").Font.Bold = true;
//((Range)mySheet.Rows[1, Missing.Value]).Font.Bold = false;
//合并单元格
//mySheet.get_Range("A2", "V2").Merge(Missing.Value);
//字体大小设置
//mySheet.get_Range("A2", "V2").Font.Size = 12;
//((Range)mySheet.Cells[1, "B"]).Font.Size = 8;//B1单元格Cells[1, "B"]等价于Cells[1,2]
//水平对齐设置
//mySheet.get_Range("A2", "V2").HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
//((Range)mySheet.Cells[2, 1]).HorizontalAlignment = XlVAlign.xlVAlignCenter;
//垂直对齐设置
//mySheet.get_Range("A2", "V2").VerticalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
//公式设置
//mySheet.get_Range("C7", "C7").FormulaR1C1 ="=SUM(C3:C6)";// "公式";
//列宽设置
//mySheet.get_Range("A2", "V2").ColumnWidth = 50;// 宽度;
//行高
//mySheet.get_Range("A2", "V2").RowHeight = 20;// 行高;
//设置列格式
//Microsoft.Office.Interop.Excel.Range myrange = mySheet.get_Range(mySheet.Cells[1, 1], mySheet.Cells[5, 1]);
//mySheet.get_Range("A12", "C12").NumberFormatLocal = "@";//文本格式
//myrange.NumberFormatLocal = "@";//文本格式
//myrange.Style.NumberFormatLocal = "[DBNum2][$-804]G/通用格式"; //通用格式
//myrange.NumberFormatLocal = "G/通用格式";
//添加行
//((Microsoft.Office.Interop.Excel.Range)mySheet.Cells[17, 2]).EntireRow.Insert(0);
//设置第10行为红色
//mySheet.get_Range((Microsoft.Office.Interop.Excel.Range)mySheet.Cells[10, 1], (Microsoft.Office.Interop.Excel.Range)mySheet.Cells[10, 200]).Select();
//mySheet.get_Range((Microsoft.Office.Interop.Excel.Range)mySheet.Cells[10, 1], (Microsoft.Office.Interop.Excel.Range)mySheet.Cells[10, 200]).Interior.ColorIndex = 3;
//单元格自动换行
//myrange.WrapText = true;
//单元格行高自动调整
//myrange.EntireRow.AutoFit();
#endregion
#region 复制行样式
// mySheet.get_Range("A4","FF4").Copy(mySheet.get_Range("A10","FF10"));//复制块区域数据
Microsoft.Office.Interop.Excel.Range range = (Microsoft.Office.Interop.Excel.Range)mySheet.Rows[4, Missing.Value];
Microsoft.Office.Interop.Excel.Range range2 = (Microsoft.Office.Interop.Excel.Range)mySheet.Rows[11, Missing.Value];
//range.Copy(range2);//复制整行包含格式样式,文字字体颜色
//mySheet.Rows[4, Missing.Value].Copy(mySheet.Rows[15, Missing.Value]);//复制整行包含格式样式,文字字体颜色
复制多行包含格式样式,文字字体颜色
//Range range12 = mySheet.get_Range((Range)mySheet.Cells[2, 1], (Range)mySheet.Cells[4, mySheet.Columns.Count]);
//range12.Copy((Range)mySheet.Cells[18, 1]);
myWorkbook.SaveAs(newFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
#endregion
//关闭Excel文件
myWorkbook.Close(false, Missing.Value, Missing.Value);
}
catch (Exception ex)
{
// 释放资源
KillAllExcel(myExcel);
mySheet = null;
myWorkbook = null;
//myExcel.Quit();
myExcel = null;
throw new Exception("" + ex.Message);
}
finally
{
// 释放资源
KillAllExcel(myExcel);
mySheet = null;
myWorkbook = null;
//myExcel.Quit();
myExcel = null;
}
3.函数调用:
[System.Runtime.InteropServices.DllImport("User32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
/// <summary>
/// 获得所有的Excel进程
/// </summary>
/// <returns>所有的Excel进程</returns>
private static List<Process> GetExcelProcesses(Microsoft.Office.Interop.Excel.Application myExcel)
{
Process[] processes = Process.GetProcesses();
List<Process> excelProcesses = new List<Process>();
IntPtr t = new IntPtr(myExcel.Hwnd);
int k = 0;
GetWindowThreadProcessId(t, out k);
for (int i = 0; i < processes.Length; i++)
{
if (processes[i].ProcessName.ToUpper() == "EXCEL")
{
if(k== processes[i].Id)
excelProcesses.Add(processes[i]);
break;
}
}
return excelProcesses;
}
private static void KillAllExcel(Microsoft.Office.Interop.Excel.Application myExcel)
{
List<Process> excelProcess = GetExcelProcesses(myExcel);
for (int i = 0; i < excelProcess.Count; i++)
{
excelProcess[i].Kill();
}
}
备注1:设置字体颜色值参考下图;
备注2:DataTest.xlsx内容如下图;其中J3是带下拉框的内容1,2,3
附录简单例子1:
System.Reflection.Missing miss = System.Reflection.Missing.Value;
//Microsoft.Office.Interop.Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
//下面这样定义,导出操作同样可以成功,但据说以下为接口,不太明白
Microsoft.Office.Interop.Excel.Application oexcel = new Microsoft.Office.Interop.Excel.Application();
//oexcel.Application.Workbooks.Add(true);
oexcel.Application.Workbooks.Add("D:\\11.XLSX");//创建新的文件,内容空白
//oexcel.Visible = true;//若是true,则在导出的时候会显示EXcel界面
if (oexcel == null)
{
MessageBox.Show("EXCEL无法启动!(可能您没有安装EXCEL,或者版本与本程序不符)", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
Workbooks obooks = oexcel.Workbooks;
Workbook obook = obooks.Add(miss);
Worksheet osheet = obook.ActiveSheet;
//Worksheet osheet = (Worksheet)obook.Sheets[1];
osheet.Name = "数据";
//创建 Range ,方便释放资源
Range rans = osheet.Cells;
rans[3, 4] = "dfgfd";
obook.SaveCopyAs("D:\\11.XLSX");
附录简单例子2:
// 导出为Excel格式文件
/// </summary>
/// <param name="dt">作为数据源的DataTable</param>
/// <param name="saveFile">带路径的保存文件名</param>
/// <param name="title">一个Excel sheet的标题</param>
public static void DataTabletoExcel(System.Data.DataTable dt, string saveFile)
{
Microsoft.Office.Interop.Excel.Application rptExcel = new Microsoft.Office.Interop.Excel.Application();
if (rptExcel == null)
{
PublicClass.HintBox("无法打开EXcel,请检查Excel是否可用或者是否安装好Excel");
return;
}
int rowCount = dt.Rows.Count;//行数
int columnCount = dt.Columns.Count;//列数
int rowIndex = 1;
int colindex = 1;
//保存文化环境
System.Globalization.CultureInfo currentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
Microsoft.Office.Interop.Excel.Workbook workbook = rptExcel.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets.get_Item(1);
worksheet.Name = "报表";//一个sheet的名称
rptExcel.Visible = true;//打开导出的Excel文件
worksheet.Cells[1, 1] = "27705";//模版号
rowIndex++;
//第二行内容
Microsoft.Office.Interop.Excel.Range rangeinfo1 = worksheet.get_Range(worksheet.Cells[rowIndex, colindex + 6],worksheet.Cells[rowIndex, colindex + 7]);
rangeinfo1.NumberFormat = "@";
worksheet.Cells[rowIndex, colindex] = "S#262229";
worksheet.Cells[rowIndex, colindex+6] = dt.Columns[13].ColumnName;
worksheet.Cells[rowIndex, colindex + 7] = dt.Rows[0][13];
worksheet.Cells[rowIndex, colindex+12] = "EAN";
//合并打印数量单元格
worksheet.Cells[rowIndex, columnCount+1] = "打印数量";
worksheet.Cells[rowIndex, columnCount+2] = "包装数量";
worksheet.get_Range(worksheet.Cells[rowIndex, columnCount + 1], worksheet.Cells[rowIndex + 2, columnCount + 1]).MergeCells = true;
worksheet.get_Range(worksheet.Cells[rowIndex, columnCount + 2], worksheet.Cells[rowIndex + 2, columnCount + 2]).MergeCells = true;
rowIndex++;
//第三行内容
worksheet.Cells[rowIndex, 1] = "貨名";
worksheet.Cells[rowIndex, 2] = "Line";
//合并第三行第二列
worksheet.get_Range(worksheet.Cells[rowIndex, 2], worksheet.Cells[rowIndex+1, 2]).MergeCells = true;
worksheet.Cells[rowIndex, 3] = "序號";
worksheet.Cells[rowIndex, 4] = "數量";
worksheet.Cells[rowIndex, 5] = "1 (EUR) size";
worksheet.Cells[rowIndex, 6] = "1a (€)";
worksheet.Cells[rowIndex, 7] = "2 (UK) size";
worksheet.Cells[rowIndex, 8] = "2a (₤)";
worksheet.get_Range(worksheet.Cells[rowIndex, 5], worksheet.Cells[rowIndex, 8]).Font.Bold = true;
worksheet.Cells[rowIndex, 9] = "4";
worksheet.Cells[rowIndex, 10] = "5";
worksheet.Cells[rowIndex, 11] = "6";
worksheet.Cells[rowIndex, 12] = "7";
worksheet.Cells[rowIndex, 13] = "8(barcode)";
worksheet.Cells[rowIndex, 14] = "9";
worksheet.get_Range(worksheet.Cells[rowIndex, 5], worksheet.Cells[rowIndex, 8]).Font.ColorIndex = 5;
rowIndex++;
//填充列标题
for (int i = 0; i < columnCount-1; i++)
{
if (i > 0)
{
worksheet.Cells[rowIndex, i + 2] = dt.Columns[i].ColumnName;
}
else
{
worksheet.Cells[rowIndex, i+1] = dt.Columns[i].ColumnName;
}
}
rowIndex++;
//创建对象数组存储DataTable的数据,这样的效率比直接将Datateble的数据填充worksheet.Cells[row,col]高
object[,] objData = new object[rowCount, columnCount];
//填充内容到对象数组
for (int r = 0; r < rowCount; r++)
{
for (int col = 0; col < columnCount-1; col++)
{
objData[r, col] = dt.Rows[r][col].ToString();
}
System.Windows.Forms.Application.DoEvents();
}
//将对象数组的值赋给Excel对象
Microsoft.Office.Interop.Excel.Range range = worksheet.get_Range(worksheet.Cells[rowIndex, 1], worksheet.Cells[rowCount+rowIndex-1, columnCount-1]);
range.NumberFormat = "@";//设置数字文本格式
Microsoft.Office.Interop.Excel.Range rangeinfo = worksheet.get_Range(worksheet.Cells[rowIndex, 4], worksheet.Cells[rowCount + rowIndex - 1, 4]);
rangeinfo.NumberFormat = "00";
range.Value2 = objData;
for (int i = 0; i < rowCount; i++)
{
if (i > 0)
{
//计算打印数量
worksheet.Cells[rowIndex + i, columnCount+1] = "=CEILING(D" + (rowIndex + i).ToString() + "*1.01+1,2)";
}
else
{
worksheet.Cells[rowIndex + i, columnCount+1] = "=CEILING(D" + (rowIndex + i).ToString() + "*1.01+1,2)";
}
}
//设置格式
rptExcel.StandardFont = "新細明體";
rptExcel.StandardFontSize = 12;
worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[rowCount+rowIndex, columnCount]).Columns.AutoFit();//设置单元格宽度为自适应
worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[rowCount+rowIndex, columnCount]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;//居中对齐
//worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[1, columnCount]).Font.Bold = true;
//worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[1, columnCount]).Font.Color= ConsoleColor.Blue;
// worksheet.get_Range(worksheet.Cells[2, 1], worksheet.Cells[rowCount + 2, columnCount]).Borders.LineStyle = 1;//设置边框
//汇总
rowIndex = rowCount + rowIndex;
worksheet.Cells[rowIndex, 4] = "=SUM(D5:D10)";
//恢复文化环境
System.Threading.Thread.CurrentThread.CurrentCulture = currentCI;
try
{
//rptExcel.Save(saveFile); //自动创建一个新的Excel文档保存在“我的文档”里,如果不用SaveFileDialog就可用这种方法
workbook.Saved=true;
workbook.SaveCopyAs(saveFile);//以复制的形式保存在已有的文档里
PublicClass.HintBox("数据已经成功导出为Excel文件!");
}
catch (Exception ex)
{
PublicClass.HintBox("导出文件出错,文件可能正被打开,具体原因:" + ex.Message);
}
finally
{
dt.Dispose();
rptExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(rptExcel);
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
GC.Collect();
KillAllExcel();
}
}
/// <summary>
/// 获得所有的Excel进程
/// </summary>
/// <returns>所有的Excel进程</returns>
private static List<Process> GetExcelProcesses()
{
Process[] processes = Process.GetProcesses();
List<Process> excelProcesses = new List<Process>();
for (int i = 0; i < processes.Length; i++)
{
if (processes[i].ProcessName.ToUpper() == "EXCEL")
excelProcesses.Add(processes[i]);
}
return excelProcesses;
}
private static void KillAllExcel()
{
List<Process> excelProcess = GetExcelProcesses();
for (int i = 0; i < excelProcess.Count; i++)
{
excelProcess[i].Kill();
}
}
附录简单例子3:
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);//建立Excel对象 空白文件无文件名
try
{
int init = 6;//从A6开始写入数据
int temp = init;
//填充数据
for (int i = 0; i < 10; i++)
{
excel.Cells[init, 1] = i + 1;//单元格A6
excel.Cells[init, 2] = i+"MATNR".ToString();//单元格B6
excel.Cells[init, 3] = i+"LABST".ToString();
excel.Cells[init, 4] = i+"MESQTY".ToString();
excel.Cells[init, 5] = i+"Diff".ToString();
((Range)excel.Rows[2, Missing.Value]).Copy(excel.Rows[init + 1, Missing.Value]);//复制整行包含格式样式
for (int j = 0; j < 5; j++)
{
((Range)excel.Rows[init + 2 + j, Missing.Value]).Insert(Missing.Value, XlInsertFormatOrigin.xlFormatFromLeftOrAbove);//插入一行
excel.Cells[init + 2 + j, 2] = j+"MATNR".ToString();
excel.Cells[init + 2 + j, 3] = j+"MBLNR".ToString();
excel.Cells[init + 2 + j, 4] = j+"ZEILE".ToString();
excel.Cells[init + 2 + j, 5] = j+"BWART".ToString();
excel.Cells[init + 2 + j, 6] = j+"MENGE".ToString();
}
temp = init + 1 + 5;//填写单个项目明细的一个轮回
init = temp + 1;//新的起点开始写第二个料号数据集明细部分
}
excel.ActiveWorkbook.SaveCopyAs("D:\\11.XLSX");
excel.ActiveWorkbook.Saved = true;
excel.Application.Workbooks.Close();
excel.Application.Quit();
excel.Quit();
}
catch (Exception ex)
{
throw ex;
}
运行的效果截图;
是一个带折叠的样式,当你点击加号可以看到明细部分内容。这个折叠样式是EXCEL的:数据---->创建组的功能 我把它放在一个EXCEL模板中,然后复制这个样式即可,代码是没法实现这个样式的。
代码体现:((Range)excel.Rows[2, Missing.Value]).Copy(excel.Rows[init + 1, Missing.Value]);//复制整行包含格式样式