C# NPOI讀取EXCEL與GDI+簡單繪圖

以前在項目中遇到過將Excel表中的座標信息讀取出來,並用這些座標信息在窗體上繪製圓形,大致預覽出形狀,在這裡主要用到了NPOI及GDI+繪圖,特把此分享記錄下來。

C# NPOI讀取EXCEL與GDI+簡單繪圖

項目要求:

1、根據要求EXCEL表第一列是ID號,要在每個圓裡顯示出來;

2、EXCEL表第三列與第四列分別是X,Y座標,無論第一個點座標是不是原點,繪製時都要在固定的地方開始;

3、EXCEL表的第四列是座標顯示信息,只有0和1,是0時顯示一種顏色,是1時顯示另外一種顏色。

部分代碼如下:

1、讀取EXCEL表放到DataGridView中,首先引用NPOI

C# NPOI讀取EXCEL與GDI+簡單繪圖

string path;

OpenFileDialog openFileDialog = new OpenFileDialog();

openFileDialog.InitialDirectory = @"./";

openFileDialog.Filter = "EXCEL2007|*.xlsx";//EXCEL2003|*.xls|

openFileDialog.RestoreDirectory = true;

openFileDialog.FilterIndex = 1;

if (openFileDialog.ShowDialog() == DialogResult.OK)

{

dt.Reset();

dt = new DataTable();

path = openFileDialog.FileName;

textBox1.Text = path;

using (FileStream fsRead = new FileStream(path, FileMode.Open, FileAccess.Read))

{

IWorkbook wk = new XSSFWorkbook(fsRead);

//new XSSFWorkbook

ISheet sheet = wk.GetSheetAt(0);

IRow currentRow = sheet.GetRow(0);

//最後一個方格的編號 即總的列數

int cellCount = currentRow.LastCellNum;

for (int i = 0; i < cellCount; i++)

{

//DataColumn dc = new DataColumn();

dt.Columns.Add(currentRow.GetCell(i).ToString());//增加列

}

for (int j = 0; j <= sheet.LastRowNum - 1; j++)

{

//DataRow dr = dt.NewRow();

dt.Rows.Add();//增加行

IRow currentRow1 = sheet.GetRow(j + 1);

if (currentRow1 != null)

{

for (int c = 0; c < currentRow1.LastCellNum; c++)

{

ICell cell = currentRow1.GetCell(c);

if (cell == null || cell.CellType == CellType.Blank)

{

//向dt中插入一個DBNull.Value

dt.Rows[j][c] = DBNull.Value;

}

else

{

//如果當前單元格不為空,則根據單元格的類型獲取數據

switch (cell.CellType)

{

//只有當單元格的數據類型是數字類型的時候使用cell.NumericCellValue來獲取值。其餘類型都使用字符串來獲取.日期類型數據插入單元格後也是CellType.NUMERIC

case CellType.Numeric:

//cell.NumericCellValue;

dt.Rows[j][c] = cell.NumericCellValue;

break;

default:

//cell.ToString();

dt.Rows[j][c] = cell.ToString();

break;

}

}

// this.dataGridView1.Rows[index].Cells[0].Value = "1";

}

}

}

dataGridView1.DataSource = dt;

}

}

else

return;

2、圖形繪製

private void PaintCircle(float x, float y, int i, int j, DataTable dtemp)

{

float dt_01x = Convert.ToSingle(dt.Rows[0][1]);

float dt_01y = Convert.ToSingle(dt.Rows[0][2]);

Graphics g = this.CreateGraphics();

g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

Brush bushO = new SolidBrush(Color.Orange);//填充的顏色

Brush bushG = new SolidBrush(Color.Green);//填充的顏色

Brush bush1 = new SolidBrush(Color.Red);//填充的顏色

if (j == 0)

{

g.FillEllipse(bushG, 400 - 1.2f*x + dt_01x, 50 + 1.2f*y - dt_01y, 18, 18);//畫填充橢圓的方法,x座標、y座標、寬、高,如果是100,則半徑為50

}

else

{

g.FillEllipse(bushO, 400 - 1.2f * x + dt_01x, 50 + 1.2f * y - dt_01y, 18, 18);//畫填充橢圓的方法,x座標、y座標、寬、高,如果是100,則半徑為50

}

g.DrawString((i + 1).ToString(), new Font("黑體", 9f, FontStyle.Bold), bush1, 400 - 1.2f * x + dt_01x, 50 + 1.2f * y - dt_01y);

g.Dispose();

bushO.Dispose();

bushG.Dispose();

bush1.Dispose();

}

3、效果動態預覽

C# NPOI讀取EXCEL與GDI+簡單繪圖

4、完整代碼較長,已存放雲盤,點贊並關注@工控上位機 ,發送私信“繪製圓”即可獲取,非常謝謝您的關注,一起學習進步。


分享到:


相關文章: