using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
using System.Data.SqlClient;
namespace ExcelOperator
{
public class ExcelOperator
{
public Application ExcelApplincation;
public Workbook ExcelWorkBook;
public Worksheet ExcelWorkSheet;
public ExcelOperator()
{
ExcelApplincation = new Application();
ExcelApplincation.Visible = true;
}
public void CreateExcel()
{
try
{
ExcelWorkBook = ExcelApplincation.Workbooks.Add();
ExcelWorkSheet = ExcelWorkBook.Worksheets[1] as Worksheet;
//写入表格
WriteExcel();
object fileName = Path.Combine(Directory.GetCurrentDirectory(), "1.xlsx");
ExcelWorkBook.SaveAs(fileName);
}
catch (System.Exception ex)
{
}
finally
{
((_Application)ExcelApplincation).Quit();
}
}
public Range this[object row, object col]
{
get { return ExcelWorkSheet.Cells[row, col]; }
}
public void WriteExcel()
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "MXC-PC";
builder.InitialCatalog = "student";
builder.UserID = "sa";
builder.Password = "south";
SqlDataAdapter adapter = new SqlDataAdapter("select *from student_info", builder.ConnectionString);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet);
string[] fields = new string[] { "学号", "姓名", "年龄", "年级", "成绩", "性别" };
for (int col = 0; col < dataSet.Tables[0].Columns.Count; col++)
{
Range range = this[1, col + 1];
range.Value2 = fields[col];
}
int row = 2;
for (int i = 0; i < dataSet.Tables[0].Rows.Count; i++)
{
for (int j = 0; j < dataSet.Tables[0].Columns.Count; j++)
{
Range range = this[row, j + 1];
range.Value2 = dataSet.Tables[0].Rows[i][j];
if (j == 4 && range.Value2 < 60) //不及格
{
range.Interior.Color = Color.Red;
}
}
row++;
}
Range range1 = this[row, 1];
range1.Value2 = "平均值";
Range rangeAge = this[row, 3];
rangeAge.Formula = string.Format("=AVERAGE(C2:C{0})", row-1);
Range rangeGrade = this[row, 4];
rangeGrade.Formula = string.Format("=AVERAGE(D2:D{0})", row - 1);
Range rangeResult = this[row, 5];
rangeResult.Formula = string.Format("=AVERAGE(E2:E{0})", row - 1);
}
}
}
//读取
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Workbook workBook = excelApp.Workbooks.Open(Path.Combine(Directory.GetCurrentDirectory(), "1.xlsx"));
Worksheet workSheet = workBook.Worksheets[1] as Worksheet;
try
{
int row = 2, col = 1;
Range range = workSheet.Cells[row, col];
while (range.Value2 != null)
{
object[] values = new object[6];
while (range.Value2 != null)
{
values[col - 1] = range.Value2;
col++;
range = workSheet.Cells[row, col];
}
DataGridViewRow viewRow = new DataGridViewRow();
viewRow.CreateCells(dataGridView1, values);
dataGridView1.Rows.Add(viewRow);
row++;
col = 1;
range = workSheet.Cells[row, col];
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
excelApp.Quit();
}