【发布时间】:2013-04-26 15:11:26
【问题描述】:
我正在将数据从 datagridview 导出到 Excel 工作表。数据由数字和字符组成。数字显示在单元格的最右侧,与左侧的字符一样。我缺少一些数字格式。我希望数字也显示在单元格的另一侧。下面是导出到excel的代码。
private void button3_Click(object sender, EventArgs e)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range oRange;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range aRangeSingle = xlWorkSheet.get_Range("A1", "A1");
aRangeSingle.ColumnWidth = 37;
Excel.Range aRangeSingle2 = xlWorkSheet.get_Range("B1", "B1");
aRangeSingle2.ColumnWidth = 65;
int i = 0;
int j = 0;
try
{
for (i = 0; i <= dataGridView2.RowCount - 1; i++)
{
for (j = 0; j <= dataGridView2.ColumnCount - 1; j++)
{
DataGridViewCell cell = dataGridView2[j, i];
xlWorkSheet.Cells[i + 1, j + 1] = cell.Value;//this has numbers also
}
}
}
catch (Exception)
{
MessageBox.Show("server not available while export to excel");
}
【问题讨论】:
-
您需要设置单元格的水平对齐属性。 oRange.HorizontalAlignment
-
不是您具体问题的答案,但请查看stackoverflow.com/questions/5059757/…。您可以填充比 2 for 循环快得多的 Excel 范围。关于您的问题:使用@andy 的解决方案。应该这样工作。