C#操作Excel
Posted 朋克
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#操作Excel相关的知识,希望对你有一定的参考价值。
public void DoMerge(string[] source)
{
Microsoft.Office.Interop.Excel.Application sourceApp = new Microsoft.Office.Interop.Excel.Application();
Workbooks sourceWbks = sourceApp.Workbooks;
_Workbook source_wbk = sourceWbks.Add(source[0]);
Sheets source_shs = source_wbk.Sheets;
Worksheet source_wsh = (Worksheet)source_shs[2];
//判断有多少行内容
int lastRow = 2; //最后一列
for (; ; lastRow++)
{
string s = ((Range)source_wsh.Cells[lastRow, 1]).Text.ToString();
if (s == "")
break;
}
//合并文件
//0已经读作初始文件了
for (int index = 1; index < source.Length; index++)
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Workbooks wbks = app.Workbooks;
_Workbook _wbk = wbks.Add(source[index]);
Sheets shs = _wbk.Sheets;
Worksheet _wsh = (Worksheet)shs[2];
int rowCount = 2;
for (; ; rowCount++)
{
string s = ((Range)_wsh.Cells[rowCount, 1]).Text.ToString();
if (s == "")
break;
for (int colCount = 1; colCount <= MergeColCount; colCount++)
source_wsh.Cells[lastRow, colCount] = ((Range)_wsh.Cells[rowCount, colCount]).Text.ToString();
lastRow++;
}
app.Quit();
Form1.Kill(app);
}
//删除合并后的BCDNP列
DeleteCol(source_wsh, 2);
DeleteCol(source_wsh, 2);
DeleteCol(source_wsh, 2);
DeleteCol(source_wsh, 11);
DeleteCol(source_wsh, 12);
DeleteCol(source_wsh, 12);
// 改日期栏格式
//逐行处理
for (int billRow = 2; ; billRow++)
{
string s = ((Range)source_wsh.Cells[billRow, 2]).Text.ToString();
if (s == "")
break;
//单号改成最后5位数字,
source_wsh.Cells[billRow, 2] = s.Substring(s.Length - 5);
//重量件数改数字
s = ((Range)source_wsh.Cells[billRow, 7]).Text.ToString();
Range myrange = (Range)source_wsh.Cells[billRow, 7];
myrange.NumberFormatLocal = "0.00_ ";
source_wsh.Cells[billRow, 7] = s;
myrange = (Range)source_wsh.Cells[billRow, 8];
myrange.NumberFormatLocal = "0";
source_wsh.Cells[billRow, 8] = ((Range)source_wsh.Cells[billRow, 8]).Text.ToString();
//修改日期栏格式
myrange = (Range)source_wsh.Cells[billRow, 1];
myrange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignGeneral;
myrange.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
myrange.ShrinkToFit = true;
source_wsh.Cells[billRow, 1] = ((Range)source_wsh.Cells[billRow, 1]).Text.ToString();
}
FileInfo f = new FileInfo(source[0]);
string fileName = f.DirectoryName + "\\" + DateTime.Now.ToString("yyyyMMdd") + "转运单.xlsx";
SaveFileDialog sfd = new SaveFileDialog();
//设置文件类型
sfd.FileName = fileName;
if (sfd.ShowDialog() == DialogResult.OK)
{
source_wbk.SaveAs(sfd.FileName);
}
sourceApp.Quit();
Form1.Kill(sourceApp);//调用kill当前excel进程
}
以上是关于C#操作Excel的主要内容,如果未能解决你的问题,请参考以下文章